博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python zip( )函数
阅读量:4170 次
发布时间:2019-05-26

本文共 1358 字,大约阅读时间需要 4 分钟。

本文介绍python中zip( )函数的使用:

>>> help(zip)

Help on built-in function zip in module __builtin__:
zip(...)
    zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
    
    Return a list of tuples, where each tuple contains the i-th element
    from each of the argument sequences.  The returned list is truncated

    in length to the length of the shortest argument sequence.

zip([seq1, ...])接受一系列可迭代对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。若传入参数的长度不等,则返回列表的长度和参数中长度最短的对象相同。

1》

>>> x=[1,2,3]
>>> y=[1,2,3]
>>> z=(1,2,3)
>>> zip(x,y,z)
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]
2》
>>> x=(1,2,3,4)
>>> y=[1,2,3]
>>> zip(x,y) #传入参数的长度不等,则返回列表的长度和参数中长度最短的对象相同
[(1, 1), (2, 2), (3, 3)]
3》
>>> x
(1, 2, 3, 4)
>>> zip(x)
[(1,), (2,), (3,), (4,)]
4》
>>> zip()
[]

5》zip()配合*号操作符,可以将已经zip过的列表对象解压

>>> x=[1,2,3]
>>> y=['a','b','c']
>>> z=[4,5,6]
>>> xyz=zip(x,y,z)
>>> xyz
[(1, 'a', 4), (2, 'b', 5), (3, 'c', 6)]
>>> zip(*xyz)
[(1, 2, 3), ('a', 'b', 'c'), (4, 5, 6)]

6》

>>> x=[5,6,7]
>>> [x] #[x]生成一个列表的列表,它只有一个元素x
[[5, 6, 7]]
>>> [x]*3 #[x] * 3生成一个列表的列表,它有3个元素,[x, x, x]
[[5, 6, 7], [5, 6, 7], [5, 6, 7]]
>>> x
[5, 6, 7]
>>> zip(*[x]*3) #zip(* [x] * 3)等价于zip(x, x, x)
[(5, 5, 5), (6, 6, 6), (7, 7, 7)]

7》

>>> name=['song','ping','python']

>>> age=[26,26,27]
>>> zip(name,age)
[('song', 26), ('ping', 26), ('python', 27)]
>>> for n,a in zip(name,age):
...     print n,a
... 
song 26
ping 26
python 27

(完)

转载地址:http://bdyai.baihongyu.com/

你可能感兴趣的文章
String Operations in Shell
查看>>
烦请解释一下“驱动表”的概念
查看>>
IPAide(IP助手) v1.01
查看>>
Oracle 11g RAC SCAN basics
查看>>
ASM appears to be running, but connect via sqlplus, says idle instance.??
查看>>
Oracle EBS R12 - Steps and Issues/Resolutions during R12.1.1 to R12.1.3 Upgration
查看>>
HW的最后一轮面试
查看>>
简易Python电话本(Simple Python Telephone Book)
查看>>
经典影视日语
查看>>
JPad 1.00(20081213)
查看>>
test the difference between "DEFAULT NULL" and "DEFAULT 0"
查看>>
一个非常方便好用的ADO数据库连接字符串生成工具
查看>>
轻松得到C# ADO.NET的各种数据库连接字符串
查看>>
DLL文件制作与在VBA调用初级进阶
查看>>
Excel VBA: Delete Module After Running VBA Code. Deleting Modules via VBA Code
查看>>
SQLPLUS 使用的一些技巧
查看>>
excel 宏表函数 get.cell
查看>>
Recover Deleted Linux Files With lsof
查看>>
<<Oracle Applications DBA 基础(第二期)>>Week 01 exercise
查看>>
<<Oracle Applications DBA 基础(第二期)>>Week 02 exercise
查看>>