0

Preface: Element-wise addition of 2 lists?

I want to write to code to have the following behavior:

[ 1, 1, ["Alpha"]]
+
[ 2, 2, ["Beta"] ]
||       ||     ||
\/       \/     \/
[3, 3, ["Alpha", "Beta"]]

in python. Is this possible without very messy comprehensions and mapping?

4

3 回答 3

7
[a + b for a, b in zip(l1, l2)]
于 2017-07-24T21:12:05.197 回答
3

是的,这是可能的,尽管在称列表理解混乱之前我会三思而后行。与两个列表一起operator.__add__传递:map

import operator
list(map(operator.__add__, l1, l2))
# [3, 3, ['Alpha', 'Beta']]
于 2017-07-24T21:10:11.243 回答
2

该解决方案使用列表推导,尽管它们远非混乱。此外,它非常易读,不需要库

a = [1, 1, ["ALPHA"]]
b = [2, 2, ["BETA"]]
c = [a[i]+b[i] for i in range(len(a))]
print(c)
于 2017-07-24T21:11:44.863 回答