Skip to main content
 首页 » 编程设计

python之如何检查列表中的所有元素是否都是整数

2025年05月04日15over140

如果我有一个列表,例如:

List = [12,6,3,5,1.2,5.5]  

有没有办法检查所有数字是否都是整数?我试过类似的东西

def isWhole(d):  
if (d%1 == 0 ) : for z in List return true. 

这显然是非常错误的。我能做什么?

请您参考如下方法:

所以你想要整数和等于整数的 float ?

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 将其应用到您的列表中和 map :

if all(map(is_whole, List)): 

或 generator expression :

if all(is_whole(d) for d in List):