有没有办法让列表理解中的两个或多个项目出列。
即我想做这样的事情:
>>> q = [1, 2, 3, 4]
>>> r = [x+y for x, y in q]
** This does not work though :( **
预期的:
>>> r
[3, 7]
有没有办法让列表理解中的两个或多个项目出列。
即我想做这样的事情:
>>> q = [1, 2, 3, 4]
>>> r = [x+y for x, y in q]
** This does not work though :( **
预期的:
>>> r
[3, 7]
>>> from itertools import izip_longest
>>> [x + y for x, y in grouper(2,q)]
[3, 7]
配方的源代码是这样的:
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
如果列表仅包含 2 个组,例如,则有效。不会工作,[1,2,3,4,5]
但会工作[1,2,3,4,5,6]
>>> q = [1, 2, 3, 4]
>>> [x+y for x, y in zip(*[iter(q)]*2)]
[3, 7]
也正如@gnibbler 所建议的那样
>>> map(sum, zip(*[iter(q)]*2))
另一种解决方案
>>> [sum(q[i:i+2]) for i in range(0,len(q),2)]
[3, 7]
>>> q=[1,2,3,4,5]
>>> [sum(q[i:i+2]) for i in range(0,len(q),2)]
[3, 7, 5]