简体   繁体   English

使用for循环汇总python中列表中的元素

[英]Summing up elements in a list in python using a for loop

While working on a program that creates bars out of sets of numbers in a list, I found that adding up items in my list doesn't work. 当在一个程序中使用列表中的数字集创建小节时,我发现将列表中的项目加起来是行不通的。 I thought the best way to do this is just to make a for loop. 我认为最好的方法就是创建一个for循环。

Here's my list: 这是我的清单:

phonelist = [[12,14,16,17,18],[16,23,54,64,32]]

And then I try to add this up with a for loop 然后我尝试将其与for循环加在一起

numphone = 0
for x in len(phonelist[0]):
    numphone = numphone + x

Yet I get this error: 但是我得到这个错误:

TypeError: 'int' object is not iterable TypeError:“ int”对象不可迭代

What should I do? 我该怎么办?

>>> phonelist = [[12,14,16,17,18],[16,23,54,64,32]]
>>> [sum(li) for li in phonelist]
[77, 189]
>>> sum([sum(li) for li in phonelist])
266

or: 要么:

>>> sum(sum(li) for li in phonelist)    # generator expression...
266

If you are trying to create individual categories, you can use a dict: 如果尝试创建单个类别,则可以使用dict:

data={'Bar {}'.format(i):sum(li) for i, li in enumerate(phonelist, 1)}
data['Total']=sum(data.values())

print data
{'Bar 2': 189, 'Bar 1': 77, 'Total': 266}

Then if you want to produce a simple bar graph: 然后,如果要生成一个简单的条形图:

for bar in sorted(data.keys()):
    print '{}: {}'.format(bar, int(round(25.0*data[bar]/data['Total']))*'*')

Prints: 印刷品:

Bar 1: *******
Bar 2: ******************
Total: *************************

len(phonelist[0]) is an int, so you can't loop over it. len(phonelist[0])是一个int,因此无法对其进行循环。 You can change that to 您可以将其更改为

for x in phonelist[0]:

This way x will take on each value of phonelist[0] . 这样, x将采用phonelist[0]每个值。

numphone = 0
for x in phonelist[0]:
    numphone = numphone + x

This should work. 这应该工作。 You iterate overt the list, not over the length of it, since the length is an integer and iterating over an integer doesn't make sense 您可以遍历列表,而不是遍历整个列表,因为长度是整数,并且遍历整数没有意义

The best solution to this is to use the sum() built-in function . 最好的解决方案是使用sum()内置函数 One method, as given in other answers to this question, is to sum each sumlist, then sum those subtotals. 如对该问题的其他答案所述,一种方法是对每个汇总列表求和,然后对这些小计求和。

However, a better solution is to flatten the sublists - this is best achieved with itertools.chain.from_iterable() . 但是,更好的解决方案是将子列表展平-最好通过itertools.chain.from_iterable()实现。

sum(itertools.chain.from_iterable(phonelist))

This is an optimal solution as it means that you do not have to perform a lot of separate sum operations, or create an intermediate list. 这是一个最佳解决方案,因为它意味着您不必执行大量单独的求和运算或创建中间列表。 It will also work lazily if your data is a lazy source, making your code more memory-efficient and spreading the processing load. 如果您的数据是惰性源,它也会懒惰地工作,从而使您的代码具有更高的内存效率并分散了处理负载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM