我有这个:
[
[ [1,1,1,0,0,0,0], [0,1,2,3,4,5,6], [1,2,3,4,5,6,7], [2,3,4,5,6,7,8], [3,4,5,6,7,8,9], [4,5,6,7,8,9,0] ]
, [ [2,2,2,0,0,0,0], [0,1,2,3,4,5,6], [1,2,3,4,5,6,7], [2,3,4,5,6,7,8], [3,4,5,6,7,8,9], [4,5,6,7,8,9,2] ]
, [ [3,3,3,0,0,0,0], [0,1,2,3,4,5,6], [1,2,3,4,5,6,7], [2,3,4,5,6,7,8], [3,4,5,6,7,8,9], [4,5,6,7,8,9,0] ]
]
我试图解决这个问题:
[
[[6, 6, 6, 0, 0, 0, 0], [0, 3, 6, 9, 12, 15, 18], [3, 6, 9, 12, 15, 18, 21], [6, 9, 12, 15, 18, 21, 24], [9, 12, 15, 18, 21, 24, 27], [12, 15, 18, 21, 24, 27, 2]]
]
它只是最深层列表中所有相对位置的总和。 现在,我已经有3个嵌套for循环,我希望你们中的一个专家可以向我展示更快更好的内容。更优雅的方式来做到这一点
答案 0 :(得分:1)
您不需要使用itertools,您可以使用列表理解和zip(*)
来完成此操作:
>>> lst = [[[1, 1, 1, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7], [2, 3, 4, 5, 6, 7, 8], [3, 4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9, 0]], [[2, 2, 2, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7], [2, 3, 4, 5, 6, 7, 8], [3, 4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9, 2]], [[3, 3, 3, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7], [2, 3, 4, 5, 6, 7, 8], [3, 4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9, 0]]]
>>> [[sum(y) for y in zip(*x)] for x in zip(*lst)]
[[6, 6, 6, 0, 0, 0, 0], [0, 3, 6, 9, 12, 15, 18], [3, 6, 9, 12, 15, 18, 21], [6, 9, 12, 15, 18, 21, 24], [9, 12, 15, 18, 21, 24, 27], [12, 15, 18, 21, 24, 27, 2]]
请注意,您当前的预期输出是一个包含列表列表的列表,这是不必要的,最好将其保存到列表列表中。
答案 1 :(得分:0)
没有列表推导的另一种解决方案:
# In Python 2.x
>>> map(lambda l: map(sum, zip(*l)), zip(*lst))
# In Python 3.x
>>> list(map(lambda l: list(map(sum, zip(*l))), zip(*lst)))
请注意,此解决方案只是概念验证,您应该使用@AshwiniChaudhary的解决方案,因为它更清晰,更易读。