您的位置:首页 > 编程语言 > Python开发

python中与序列相关的内建函数

2012-11-15 18:15 651 查看

1.zip用法

定义:zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。利用*号操作符,可以将list unzip(解压)

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

>>> b = [4,5,6]

>>> c = [4,5,6,7,8]

>>> zipped = zip(a,b)

[(1, 4), (2, 5), (3, 6)]

>>> zip(a,c)

[(1, 4), (2, 5), (3, 6)]

>>> zip(*zipped)

[(1, 2, 3), (4, 5, 6)]

2.enumerate 用法

在for循环中得到计数,参数可遍历的变量,如:字符串,列表等,返回一个enumerate类

>>> s=('a','b','c','d')

>>> for i,album in enumerate(s):

... print i,album

...

0 a

1 b

2 c

3 d

3.sort用法

>>> albums = ('Poe', 'Gaudi', 'Freud', 'Poe2')

>>> for album in sorted(albums):

... print album,

...

Freud Gaudi Poe Poe2
本文出自 “浮云飘雪” 博客,请务必保留此出处http://meizimm.blog.51cto.com/1791794/1060886
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: