Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字符串列表中添加数字_Python_String_List_Average - Fatal编程技术网

Python 从字符串列表中添加数字

Python 从字符串列表中添加数字,python,string,list,average,Python,String,List,Average,我在脚本中打开一个列表,搜索与“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'] 我想做的是从第三列中得到所

我在脚本中打开一个列表,搜索与“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']
我想做的是从第三列中得到所有的值,然后求和得到结果30920,然后计算并打印平均值6184。到目前为止,我有以下代码

   total = int(row[2])
   total2 = sum(total)
   print total2
但是,我得到以下错误

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

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

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

使用for循环而不是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将其解释为生成器表达式。您可以阅读更多有关它的信息

总计
应该是一个
列表

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

由于您还想得到平均值,所以相应地,您也必须获得过滤列表的长度。 您可以相应地修改上面的任何代码,我将使用@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

嗨,哈迪罗,我用你的代码部分替换了我的代码部分,但是我得到了以下错误。total2=sum(如果i中的'2011'为i,则dL中的i为i[2])TypeError:不支持+:'int'和'str'的操作数类型,您知道为什么吗???@user2603519我刚刚修复了您的注释:)谢谢,这非常有效。如果我试图计算平均值,我将如何使用列表的len来计算平均值??但这并不是一个真正的清单??谢谢,海德罗的工作非常完美。这完美地解决了我的问题。我试图使用您在循环中提供的代码,但我得到了一个值分割错误。你能帮忙吗??我需要提出一个新问题吗???@AshwiniChaudhary谢谢你纠正我。。。它的if,not是…:)注意:当你说“行[2]”时,你是指“第三列”;-)不是“第三排”,如果你正在做任何非琐碎的数据,学习熊猫包,它使这样的事情变得容易。