解析包含Str和Ints的列表

时间:2014-11-13 17:33:43

标签: python string list int

我要做的是选择一个像“['史密斯','13','19','8','12']这样的清单,而我正试图把它从中取出来将它们全部加起来计算平均值。任何人都知道如何做到这一点?

3 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

# go through each member of your list and call the 
# builtin string method `isdigit` check out the documentation
digits = [int(s) for s in your_list if s.isdigit()]
# use the built in `sum` function and the builtin `len` function
sum(digits) / len(digits)

答案 1 :(得分:0)

使用try

sum = 0
number_of_ints = 0
for items in ['Smith', '13', '19', '8', '12']:
    try:
        sum += int(items)
        number_of_ints+=1
    except:
        pass
print sum/number_of_ints

基本上,这会将其添加到sum。如果失败,它会继续。

答案 2 :(得分:0)

试试这个:

myList = ['Smith', '13', '19', '8', '12']
count = 0
total = 0

for i in myList:
    if i.isdigit():
        count += 1
        total += int(i)

average = total / count