【问题标题】:How to check if list only contains numbers [duplicate]如何检查列表是否仅包含数字[重复]
【发布时间】:2020-07-21 05:05:25
【问题描述】:

我正在努力编写一个程序来确定列表中是否只有数字,所以是浮点数还是整数。没有什么特别像“True”是1或“A”的ASCII码或类似的东西。我想检查列表以确保它只有浮点数或整数。 到目前为止,这是我的代码,但它并不适用于所有情况。

list1 = [-51,True]
for i in list1:
    if (isinstance(i,int))==False and (isinstance(i,float)==False):
        print("None")

在这种情况下,它不会打印“无”。什么时候应该为“真”。 有什么想法吗?

【问题讨论】:

标签: python list numbers


【解决方案1】:

你可以使用:

all(isinstance(e, (int, float)) for e in list1)

【讨论】:

  • Imo 最清晰的方法 - ++.
  • 谢谢你,这太棒了gg
【解决方案2】:

发现以下逻辑类型方法存在问题。

mylist = ["name", 6, True]
types = []
for i in mylist:
    types.append(isinstance(i, (int,float,complex)))


#checking whether it has two types or all aren't a number    
if len(set(types))>1 or sum(types)==0:
    print("it hasn't only numbers")   
else:
    print("it has only numbers")

mylist_2 = [7, 6, 2]
types = []

for i in mylist_2:
    types.append(isinstance(i, (int,float,complex)))

if len(set(types))>1 or sum(types)==0:
    print("it hasn't only numbers")   
else:
    print("it has only numbers")       


#approach 2 from other answer:
list1 = [True,False,True]
all(isinstance(e, (int, float)) for e in list1) #True

【讨论】:

    【解决方案3】:
    import numbers
    all(isinstance(x, number.Number) for x in the_list)
    

    【讨论】:

    • 应该是import numbers 吗?如果是这样,它对布尔值没有帮助:isinstance(False, numbers.Number) is True
    • 啊,是的。修正了错字。在 Python 中,boolint 的子类。我想isinstance(x, (float, int)) 会这样做,如果这就是我们想要的,虽然还有其他数字类型,比如complex
    猜你喜欢
    • 2018-06-20
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    相关资源
    最近更新 更多