我想了解zip
的功能。如果我有以下循环:
for input_value, time_diff in zip(mylist1, mylist2):
# some stuff
是否相当于:
for input_value in mylist1:
for time_diff in mylist2:
# some stuff
如果是这样,这意味着它只是用于压缩嵌套循环,不是吗? 谢谢
答案 0 :(得分:0)
这些是等价的:
# assuming len(mylist1) == len(mylist2)
for i in range(len(mylist1)):
input_value = mylist1[i]
time_diff = mylist2[i]
# do stuff
for input_value, time_diff in zip(mylist1, mylist2):
# do stuff
从拉链拉链拉链。采用两个(或更多)列表并通过索引将它们捆绑在一起。查看文档中的示例。 https://docs.python.org/2/library/functions.html#zip
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]