在循环中检入仅列表中的数字

时间:2017-11-09 14:09:45

标签: python python-3.x list while-loop

我是python的新手,想知道如果列表只包含数字,我可以用while循环检查... else:print(“抱歉只允许数字”)

numbers = [34, 39, 110, 303, 889, 223, 982, 7676]

def getsSumVersionTwo(listOfStuff):
    sumNumbers = 0
    for x in listOfStuff:
        sumNumbers += x
        return sumNumbers
print(getsSumVersionTwo(numbers))
getsSumVersionTwo(numbers)

6 个答案:

答案 0 :(得分:2)

假设“数字”表示整数,请使用:

all(isinstance(n, int) for n in numbers)

正如您在此示例中所见:

>>> numbers = [34, 39, 110, 303, 889, 223, 982, 7676]
>>> all(isinstance(n, int) for n in numbers)
True

答案 1 :(得分:1)

numbers = [34, 39, 110, 303, 889, 223, 982, 7676]

for x in numbers:
    if not str(x).isdigit():
        print("sorry only numbers allowed")

答案 2 :(得分:1)

def getSum(l):
    try:
        res = 0
        for i in l:
            res += i
        return res
    except:
        print('Only numbers')

def getSum(l):
    try:
        return sum(l)
    except:
        print('Only numbers')

答案 3 :(得分:1)

您将哪种类型定义为“数字”? int,long 你可以这样做:

numbers = [34, 39, 110, 303, 889, 223, 982, 7676]
numbers_type = (long, int) # add more types like double float, complex

然后检查:

if all(isinstance(n, numbers_type) for n in numbers):
       return sum
else:
     print("sorry only numbers allowed")
     raise ValueError("sorry only numbers allowed")

答案 4 :(得分:0)

如果你想允许所有数字类型(int,float等等),你可以检查列表中的每个元素,如果它是Number的实例(因为python中的每个数字类型)继承自Number)。

from numbers import Number

def only_contains_numbers(collection):
    for n in collection:
        if not isinstance(n, Number):
            return False

    return True

答案 5 :(得分:0)

这是单线解决方案:

a = any(type(i) not in(int,long) for i in numbers)
if a is True:
    print("sorry only numbers allowed")