Python3.6内置函数(67)——zip

英文文档 zip(*iterables) Make an iterator that aggrega

英文文档

  • zip(*iterables)

    Make an iterator that aggregates elements from each of the iterables.

    Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted.

zip()

zip(*iterables)

1、函数功能是聚合传入的每个迭代器中相同位置的元素,返回一个新的元组类型迭代器。

>>> x = [1,2,3]>>> y = [4,5,6]>>> xy = zip(x,y)>>> xy #xy的类型是zip类型0x0429C828 >#导入Iterable>>> from collections import Iterable>>> isinstance(xy,Iterable) #判断是否可迭代对象True>>> list(xy) #结果[(1, 4), (2, 5), (3, 6)]

2、如果传入的迭代器长度不一致,最短长度的迭代器迭代结束后停止聚合。

>>> x = [1,2,3] #长度3>>> y = [4,5,6,7,8] #长度5>>> list(zip(x,y)) # 取最小长度3[(1, 4), (2, 5), (3, 6)]

3、如果只传入一个迭代器,则返回的单个元素元组的迭代器。

>>> list(zip([1,2,3]))[(1,), (2,), (3,)]

4、如果不传入参数,则返回空的迭代器。

>>> list(zip())[]

5、zip(*[iter(s)]*n)等效于调用zip(iter(s),iter(s),...,iter(s))。

>>> x = [1,2,3]

>>> list(zip(*[x]*3))

[(1, 1, 1), (2, 2, 2), (3, 3, 3)]

>>> list(zip(x,x,x))

[(1, 1, 1), (2, 2, 2), (3, 3, 3)]

小结

希望通过上面的操作能帮助大家。如果你有什么好的意见,建议,或者有不同的看法,希望你留言和我进行交流、讨论。

打开APP阅读更多精彩内容