是否有更好的方法将元素求和到不同长度的列表?



有更好的方法吗?也许用itertools或者operator,或者别的什么?

我正在这样做。

main_tx = [100, 200]
add_tx = [1, 2, 3]
tx = []
for x in main_tx:
for user_x in add_tx:
t = x + user_x
tx.append(t)
print(tx) #[101, 102, 103, 201, 202, 203]

列表推导式:

>>> [x + y for x in main_tx for y in add_tx]
[101, 102, 103, 104, 201, 202, 203, 204]
>>> 

是的,你绝对可以使用itertools和它的product函数来迭代给定可迭代对象(在你的例子中是两个list对象)的笛卡尔积:

from itertools import product
main_tx = [100, 200]
add_tx = [1, 2, 3]
tx = []
for x, user_x in product(main_tx, add_tx):
tx.append(x + user_x)

现在,您可以使用列表推导来更高效、更python化地完成它:

tx = [x + user_x for x, user_x in product(main_tx, add_tx)]

同样,正如@don't talk just code评论中提到的,你也可以这样做:

tx = list(map(sum, product(main_tx, add_tx)))

这可能是达到结果的最有效的方法

最新更新