如何检查列表中的所有元素是否都是整数 [英] How to check if all elements in a list are whole numbers
本文介绍了如何检查列表中的所有元素是否都是整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个列表,例如:
If I have a list such as :
List = [12,6,3,5,1.2,5.5]
有没有一种方法可以检查所有数字是否都是整数?我尝试过类似的
Is there a way I can check if all the numbers are whole numbers? I tried something like
def isWhole(d):
if (d%1 == 0 ) : for z in List return true.
这显然是错误的.我该怎么办?
That is obviously terribly wrong. What can I do?
推荐答案
所以您想要整数和等于整数的浮点数?
So you want integers and floats that are equal to integers?
def is_whole(d):
"""Whether or not d is a whole number."""
return isinstance(d, int) or (isinstance(d, float) and d.is_integer())
使用中:
>>> for test in (1, 1.0, 1.1, "1"):
print(repr(test), is_whole(test))
1 True # integer
1.0 True # float equal to integer
1.1 False # float not equal to integer
'1' False # neither integer nor float
然后您可以使用 all
和
You can then apply this to your list with all
and map
:
if all(map(is_whole, List)):
或生成器表达式:
if all(is_whole(d) for d in List):
这篇关于如何检查列表中的所有元素是否都是整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文