解析包含Str和int的列表

2024-04-20 05:29:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我要做的是取一个像“['Smith','13','19','8','12']”这样的列表,我要从中取出int,把它们加起来计算平均值。有人知道怎么做吗?你知道吗


Tags: 列表int平均值smith
3条回答

使用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。如果失败了,它还会继续。你知道吗

试试这个:

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

你可以这样做:

# 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)

相关问题 更多 >