python zip( )函数
来源:互联网 发布:上海华东理工网络教育 编辑:程序博客网 时间:2024/05/17 06:42
本文介绍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
(完)
- python zip函数说明
- Python的zip函数
- Python的zip函数
- Python的zip函数
- python zip函数
- Python的zip函数
- Python的zip函数
- python的zip函数
- Python的zip函数
- Python的zip函数
- python zip函数
- Python的zip函数
- python内置函数zip
- Python 的zip函数
- python zip 函数
- Python的zip函数
- python 的 zip 函数
- python的zip函数
- [leetcode] 【数组】 60. Permutation Sequence
- 003 创建Android应用程序的工程
- 【一天一道LeetCode】#56. Merge Intervals
- BZOJ 4566: [Haoi2016]找相同字符
- JDK1.6.0+Tomcat6.0+myeclipse6.5的安装配置
- python zip( )函数
- 125. Valid Palindrome
- 【STL】back_inserter与back_insert_iterator
- hdu5690All X 「矩阵快速幂」
- Notification的几种用法(API不同)
- 从零开始学_JavaScript_系列(20)——js系列<7>(函数原型的两种声明方式、函数的作用域)
- BZOJ 4566: [Haoi2016]找相同字符
- iOS多线程的初步研究(七)-- dispatch对象
- mysql 导入excel