0

suppose I have a list as

mylist = [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15],[16,17,18]]

If I want to add element-by-element then I can use logic as:

[x+y for x,y in zip(mylist[0],mylist[1],mylist[2],mylist[3],mylist[4],mylist[6]]

and it will give sum of columnwise elements. But the problem is , writing each index of mylist inside zip function is somewhat awkward and vague if mylist happens to be list of say 1000 lists and I need to do the element by element operation.

I tried putting loop inside the zip function but it doesn't work. So any idea for that??

It should work like

zip(for k in mylist) # or something else

Thanks

4

2 回答 2

3

总结所有第一个元素,所有第二个元素等等:

In [2]: [sum(k) for k in zip(*mylist)]
Out[2]: [51, 57, 63]

请注意,输出中的每个数字都是len(mylist)数字的总和:

In [3]: zip(*mylist)
Out[3]: [(1, 4, 7, 10, 13, 16), (2, 5, 8, 11, 14, 17), (3, 6, 9, 12, 15, 18)]

*运算符解包mylist以便其项目成为单独的参数zip

于 2013-10-15T10:31:06.057 回答
2

另一种在这里看起来更明显的方法是在解压列表中使用内置的mapwithsumzip

>>> map(sum, zip(*mylist))
[51, 57, 63]

如果您是生成器的粉丝,以下内容可能会增加一些好处

>>> from itertools import izip, imap
>>> list(imap(sum, izip(*mylist)))
[51, 57, 63]
于 2013-10-15T10:52:32.623 回答