【问题标题】:Adding the numbers from a string list从字符串列表中添加数字
【发布时间】:2013-07-21 06:37:30
【问题描述】:

我在脚本中打开一个列表并搜索与“2011”匹配的内容,并使用以下代码打印“2011”字符串

for row in dL:
    if "2011" in row:
        print row

并得到以下输出

['2011', 'randome', '6200']
['2011', 'marks', '6020']
['2011', 'man', '6430']
['2011', 'is', '6040']
['2011', 'good', '6230']

我要做的是从第 3 列获取所有值并将它们相加得到结果 30920,然后计算并打印平均值 6184。到目前为止,我有以下代码。

   total = int(row[2])
   total2 = sum(total)
   print total2

但是我得到以下错误

total2 = sum(total)
TypeError: 'int' object is not iterable

如何修复此错误并创建总数和平均值?

【问题讨论】:

  • 注意:当你说'row[2]'时,你的意思是'第三列' ;-) 不是'第三行'跨度>
  • 另外,如果你正在做任何重要的数据处理,请学习 pandas 包,它会让这样的事情变得简单。

标签: python string list average


【解决方案1】:

您想查找所有列表的总和,而不是专门从一个列表中查找(正如您所尝试的那样)。

使用 list comprehension 代替 for 循环:

total2 = sum(int(i[2]) for i in dL if '2011' in i)

求平均值:

average = total2 / float(len([int(i[2]) for i in dL if '2011' in i])) # In python 3, the float() is not needed

列表推导式是一种快速制作列表的方法。以这个为例:

result = []
for i in range(1, 4):
    result.append(i**2)

结果将包含:

[1, 4, 9]

但是,这可以缩短为列表理解:

[i**2 for i in range(1,4)]

返回相同的东西。

当我打电话给sum() 并且我没有在理解周围加上括号的原因是因为我不需要。 Python 将其解释为 生成器表达式。你可以阅读更多关于它here

【讨论】:

  • 嗨 Hadiro 我用您的部分替换了我的全部代码部分,但是我收到以下错误。 total2 = sum(i[2] for i in dL if '2011' in i) TypeError: unsupported operand type(s) for +: 'int' and 'str' 你知道这是为什么吗??
  • @user2603519 我刚刚修复了你评论的问题:)
  • 感谢这个作品很漂亮。如果我试图计算平均值,我将如何使用列表的 len 来计算?但它不是一个真正的列表??
  • 感谢 Haidro 完美运行。这完美解决了我的问题
  • 海德罗。我正在尝试使用您在循环中提供的此代码,但出现值除法错误。你能帮忙吗?我需要提出一个新问题吗??
【解决方案2】:

total 应该是list。

total = [int(row[2]) for row in dL if '2011' in row]    # totals in a list
total2=sum(total)                                       # total of totals. :P
print total2                                            # print total
average = total2/len(total)                             # get average
print average                                           # print average

【讨论】:

    【解决方案3】:

    由于您还想获得平均值,因此您还必须获取过滤列表的长度。 您可以相应地修改上述任何代码,我将使用@haidro 的答案。

    l = [int(i[2]) for i in dL if '2011' in i]   #to get filtered list
    total2 = sum(l)      #total of list elemnents
    avg = total2/len(l)   #average of list elements
    

    【讨论】:

    • @AshwiniChaudhary 感谢您纠正我......如果,不是...... :)
    猜你喜欢
    • 2022-12-22
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多