Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一系列格式的列表:
a = [1,2,3,4,5,6,7] b = [1,2,3,4,5,6,7]
如何将相应的值加在一起以创建一个新列表,例如:
1加1,2加2...
c = [2,4,6,8,10,12,14]
注意:每个列表中有相同数量的值。
与zip:list comprehension-
zip
list comprehension
>>> [x+y for x, y in zip(a, b)] [2, 4, 6, 8, 10, 12, 14]
zip与列表一起使用时,创建一个list由 n 个元素组成的元组。n所以,在这里你会得到一个2-element元组列表:
list
n
2-element
>>> zip(a, b) [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7)]