【发布时间】:2017-07-10 02:14:15
【问题描述】:
我正在尝试按索引汇总一堆列表,例如:
a = [[1,2,3], [2,3,4], [3,4,5]]
output = [ reduce(lambda x, y: x[_count] + y[_count], a)
if _count in [0,2] else "" for _count in xrange(len(a)) ]
它一定适合我,预期的输出是:
>>> output
[6, "", 12]
但我得到了:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
TypeError: 'int' object has no attribute '__getitem__'
可能我不了解reduce的引擎。
我做错了吗?
【问题讨论】:
-
为什么将
reduce与列表理解一起使用? -
我认为reduce会返回一个int,我需要迭代只是为了总结特定的索引。如果有类似的东西,我全神贯注
-
等一下,你想怎么求和?
a[0][0]+a[0][1]+...或a[0][0]+a[1][0]+... -
你为什么要对索引求和?
标签: python-2.7 lambda sum reduce