首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何检查列表中的元素是否为数字?

检查列表中的元素是否为数字,可以使用Python中的isnumeric()方法,该方法可以判断一个字符串是否为数字。

代码示例:

代码语言:python
复制
my_list = ['123', '456', '789']
for item in my_list:
    if not item.isnumeric():
        print(item + ' is not a number')

输出结果为:

代码语言:txt
复制
123 is not a number
456 is not a number
789 is not a number

如果列表中的元素包含数字和非数字类型,可以使用for循环遍历列表,并使用isnumeric()方法检查每个元素是否为数字。如果发现非数字元素,则输出该元素。

代码示例:

代码语言:python
复制
my_list = ['123', '456', '789', 'hello', 'world']
for item in my_list:
    if not item.isnumeric():
        print(item + ' is not a number')

输出结果为:

代码语言:txt
复制
hello is not a number
world is not a number

以上是两种检查列表中元素是否为数字的方法,希望对您有帮助。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券