zip接受多个序列对象作为参数,返回一个tuple的序列,细节如下:
zip(*iterables)
Make an iterator that aggregates elements from each of the iterables.
Returns an iterator of tuples, where the i-th tuple contains thei-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.
>>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> zipped = zip(x, y) >>> list(zipped) #python3以后,需要list [(1, 4), (2, 5), (3, 6)] >>> x2, y2 = zip(*zip(x, y))#解压 >>> x == list(x2) and y == list(y2) True
1)只有一个序列作为参数时:
>>> x = [1,2,3]
>>> x1 = zip(x)
>>> list(x1)
[(1,), (2,), (3,)]
2)无参时
>>> list(zip())[]
3)zip([x]*3) 与 zip(*[x]*3)
>>> x = [1,2,3]
>>> [x]*3
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> list(zip([x]*3))
[([1, 2, 3],), ([1, 2, 3],), ([1, 2, 3],)]
>>> list(zip(*[x]*3))
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]
原因:在函数调用中使用*list/tuple的方式表示将list/tuple分开,作为位置参数传递给对应函数(前提是对应函数支持不定个数的位置参数)