list_a = ['pratik', 'rahul', 'messi', 342, 34.10]
def my_sum_and_count(abc):
sum = 0
for i in abc:
if isinstance(i, int) or isinstance(i, float):
sum = sum + i
return sum
print(my_sum_and_count(list_a))
答案 0 :(得分:1)
list_a = ['pratik', 'rahul', 'messi', 342, 34.10]
def my_sum_and_count(abc):
sum = 0
for i in abc:
if isinstance(i, (int, float)):
sum = sum + i
return sum
print(my_sum_and_count(list_a))
output -> 376.1
但如果您的列表是:
list_a = ['pratik', 'rahul', 'messi', '342', '34.10']
然后你的out_put是:
0
最好首先检查列表中的所有元素是否为str:
all(isinstance(item, str) for item in my_list)
这将打印True(如果所有元素都是str)和False(如果至少一个元素是整数)
如果输出为true,则必须打印例如:(可以' t sum str)因为我们没有整数
所以最终版应该是:
list_a = ['pratik', 'rahul', 'messi', 342, 34.10]
def my_sum_and_count(abc):
sum = 0
if (all(isinstance(item, str) for item in abc)):
return " all elements type are str can't be sum "
else:
for i in abc:
if isinstance(i, (int, float)):
sum = sum + i
return sum
print(my_sum_and_count(list_a))
答案 1 :(得分:0)
可以使用numpy库来评估数字/非数字的条目。
import numpy as np
list_a = ['pratik', 'rahul', 'messi', 342, 34.10]
list_b = ['pratik', 'rahul', 'messi', '342', '34.10']
def calculate_sum(l):
arr = np.genfromtxt(np.array(l).astype('bytes'))
return np.nansum(arr)
print(calculate_sum(list_a))
print(calculate_sum(list_a))
返回:
376.1
376.1