python序列处理函数

来源:互联网 发布:js div classname 编辑:程序博客网 时间:2024/06/07 06:19

len() 、max()、min( )

字符串、list、tuple都属于序列;字典不属于序列,属于映射的数据结构,但是这三个函数也仍然适用于字典的数据结构。

>>> s'hello world'>>> l[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> t(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)>>> max(s)'w'>>> max(l)9>>> max(t)9>>> min(s)' '>>> min(l)0>>> min(t)0>>> len(s)11>>> len(l)10>>> len(t)10

三个函数也可以运用于字典这种数据结构。

>>> d = {'a':s, 'b':l, 'c':t, 'd':s}>>> d{'a': 'hello world', 'c': (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), 'b': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 'd': 'hello world'}>>> max(d) #字典的最大的key'd'>>> min(d) #字典最小的key'a'>>> len(d)4

zip

zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]Return a list of tuples, where each tuple contains the i-th elementfrom each of the argument sequences.  The returned list is truncatedin length to the length of the shortest argument sequence.

zip函数参数为任意数量(0个或0个以上)的序列,生成的结果如上面所示,返回值为一个list,list的每一个item都是一个元组。生成结果list的长度与所有参数序列的最小的len一致。

>>> l1 = [1, 2, 3]>>> l2 = ['a', 'b', 'c']>>> l3 = [4, 5, 6]>>>> zip() #接收0个序列参数[]>>> zip(l1) #接收一个序列参数[(1,), (2,), (3,)]>>> zip(l1, l2)[(1, 'a'), (2, 'b'), (3, 'c')]>>> zip(l1, l2, l3)[(1, 'a', 4), (2, 'b', 5), (3, 'c', 6)]

序列参数的长度也可以不一致,但是生成结果list的长度与所有参数序列的最小的len一致。l1len为3,l4的len为5,那么生成结果的len为3。
注:map函数就不一样了,长度会自动用None自动补全, 生成结果的len为5

>>> l1 = [1, 2, 3]>>> l4 = [4, 5, 6, 7, 8]>>> zip(l1, l4)[(1, 4), (2, 5), (3, 6)]>>> map(None, l1, l4) [(1, 4), (2, 5), (3, 6), (None, 7), (None, 8)]
0 0
原创粉丝点击