上QQ阅读APP看书,第一时间看更新
The zip function
zip is useful when you have N lists of M elements, and you need to transpose them, so as to get M lists of N elements. Similar to range, it will return a generator object:
data1, data2 = (1, 2, 3, 4, 5), ('A', 'B', 'C', 'D', 'E')
result = list(zip(data1, data2))
result
>>> [(1, 'A'), (2, 'B'), (3, 'C'), (4, 'D'), (5, 'E')]
zip can also be done in reverse by using the result variable as args:
list(zip(*result))
>>> [(1, 2, 3, 4, 5), ('A', 'B', 'C', 'D', 'E')]
zip can also be used to create data structures:
dict(zip(data1, data2))
>>> {1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E'}