Python 中检查列表中的所有元素是否都是整数
使用 all()
函数检查列表中的所有元素是否都是整数,例如 if all(isinstance(item, int) for item in my_list):
。 如果列表中的所有元素都是整数,则 all()
函数将返回 True,否则返回 False。
my_list = [3, 5, 8]
if all(isinstance(item, int) for item in my_list):
# 👇️ this runs
print('All of the items in the list are integers')
else:
print('Not all of the items in the list are integers')
我们使用生成器表达式来遍历列表。
生成器表达式用于对每个元素执行某些操作或选择满足条件的元素子集。
在每次迭代中,我们检查当前项目是否为整数。
如果传入的对象是传入类的实例或子类,则 isinstance
函数返回 True。
print(isinstance(100, int)) # 👉️ True
print(isinstance(3.14, int)) # 👉️ False
print(isinstance('hello', int)) # 👉️ False
all()
内置函数将可迭代对象作为参数,如果可迭代对象中的所有元素都为真(或可迭代对象为空),则返回 True。
my_list = [3, 5, 8]
if all(isinstance(item, int) for item in my_list):
# 👇️ this runs
print('All of the items in the list are integers')
else:
print('Not all of the items in the list are integers')
如果 all()
函数遇到不是整数的项,就会短路返回 False。
如果我们需要从列表中过滤掉任何非整数值,则可以使用列表理解。
my_list = ['one', 3, 'two', 5, 'four', 8]
only_ints = [item for item in my_list if isinstance(item, int)]
print(only_ints) # 👉️ [3, 5, 8]
列表推导遍历列表并过滤掉任何非整数值。
请注意
,如果提供的可迭代对象为空,则all()
函数会针对任何条件返回 True。
my_list = []
if all(isinstance(item, int) for item in my_list):
# 👇️ this runs
print('All of the items in the list are integers')
else:
print('Not all of the items in the list are integers')
# 👇️ True
print(all(isinstance(item, int) for item in my_list))
如果我们需要处理列表为空的情况,请检查其长度。
my_list = []
if len(my_list) > 0 and all(isinstance(item, int) for item in my_list):
print('All of the items in the list are integers')
else:
# 👇️ this runs
print('Not all of the items in the list are integers')
我们使用了布尔 and
运算符,因此要运行 if
块,必须满足两个条件。
该列表的长度不大于 0,因此运行 else 块。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。