让我们说一个清单如下:
ExampleList = [2,4,7,4,2,"randomword",23,42,2,1,4,-53,"newrandomword",32,5,2,3]
如何仅添加数字?
答案 0 :(得分:4)
您可以使用以下生成器表达式,它将在列表中添加所有ints
:
l = [2,4,7,4,2,"randomword",23,42,2,1,4,-53,"newrandomword",32,5,2,3]
sum(i for i in l if isinstance(i,int))
# 80
答案 1 :(得分:2)
这将处理所有数字:)
>>> import numbers
>>> x
[2, 4, 7, 4, 2, 'randomword', 23, 42, 2, 1, 4, -53, 'newrandomword', 32, 5, 2, 3, 1.02]
>>> sum(y for y in x if isinstance(y, numbers.Number))
81.02
答案 2 :(得分:0)
您还可以使用功能filter()
:
l = [2,4,7,4,2,"randomword",23,42,2,1,4,-53,"newrandomword",32,5,2,3]
sum(filter(lambda x: isinstance(x, int), l))
# 80
答案 3 :(得分:0)
通过编程,您可以总结如下:
l = [2,4,7,4,2,"randomword",23,42,2,1,4,-53,"newrandomword",32,5,2,3]
s=0
for i in l:
try:
s+=int(i)
except ValueError:
print('not a rumber')
print('sum of number is:',s)