python zip

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分开,作为位置参数传递给对应函数(前提是对应函数支持不定个数的位置参数)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值