[英]Math operations with lists using integers from nested lists
我有:
List1 = [100, 200, 300]
List2 = [[34,35,36],[0,1,2,3],[0,1,2]]
如何將List1
的每個元素與List2
每個列表中的每個元素相加?
我想要:
List3 = [[134,135,136],[200,201,202,203],[300,301,302]]
我試着按照以下方式做一些事情:
for i in List2:
[sum(x) for x in zip(List1, i)]
但我沒有得到正確的答案。
提前致謝。
如果你想使用列表理解,你可以寫:
>>> [[x + a for a in lst] for x, lst in zip(List1, List2)]
[[134, 135, 136], [200, 201, 202, 203], [300, 301, 302]]
(這假設兩個列表的長度相同;如果不是,您可能希望使用itertools庫中的zip_longest
填充較短的列表。)
我可能會建議稍微不同的實現:
List3 = map(lambda x, y: [z + x for z in y], List1, List2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.