Python序列——序列操作

Python中的序列包括,字符串、列表、元组。本文介绍序列的通用操作。

1. 切片中的None

>>> s = 'abcdefg'
>>> for i in range(-1, -len(s), -1):
...     print s[:i]
... 
abcdef
abcde
abcd
abc
ab
a
>>> for i in [None] + range(-1, -len(s), -1):
...     print s[:i]
... 
abcdefg
abcdef
abcde
abcd
abc
ab
a
>>> s[::-1]
'gfedcba'
>>> 

2. 类型转换

  • list(iter)
  • str(obj)
  • unicode(obj)
  • basestring()
  • tuple(iter)

3. 序列内建函数

  • enumerate(iter)
  • len(seq)
  • max(iter, key=None)
  • max(arg0, arg1,…,key=None)
  • min(iter, key=None)
  • min(arg0, arg1,…,key=None)
  • reversed(seq)
  • sorted(iter, func=None, key=None, reverse=False)
  • sum(seq, init=0)
  • zip([it0, it1,…,itN])
>>> for i in enumerate(s):
...     print i
... 
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(4, 'e')
(5, 'f')
(6, 'g')
>>> len(s)
7
>>> max(s)
'g'
>>> min(s)
'a'
>>> for i in reversed(s):
...     print i
... 
g
f
e
d
c
b
a
>>> sorted(s, reverse=True)
['g', 'f', 'e', 'd', 'c', 'b', 'a']
>>> l = range(7)
>>> l
[0, 1, 2, 3, 4, 5, 6]
>>> sum(l)
21
>>> zip(s,l)
[('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6)]
>>> 
posted @ 2017-10-22 15:50  枫竹梦  阅读(827)  评论(0编辑  收藏  举报