python序列的使用

󰃭 2016-04-11

序列之通用操作

pytho中,最基本的数据结构就是序列。

什么是序列:

>>> numbers = [1,2,3,4,5,6,7,8,9,0]
>>> greeting = u'Hello, world!'
>>> names = ('Alice','Tom','Ben','John')

##python内建序列种类##

共有6种:

列表,元组,字符串,Unicode字符串,buffer对象,xrange对象。

##序列通用操作 ##

python中所有的序列都支持下面的8种操作。

###索引### 序列中所有元素都是有编号的—-从0开始

可以通过索引获取元素:

>>> greeting[0]
'H'
>>> names[3]
'John'

可以通过索引重新赋值:

>>> numbers[2] = 15
>>> numbers
[1, 2, 15, 4, 5, 6, 7, 8, 9, 0]

###分片###

分片操作对于提取序列的一部分很有用。

分片通过冒号相隔的2个索引值来实现:

>>> numbers[3:5]
[4, 5]

分片常用操作:

取序列最后几个元素:
>>> numbers[7:]
[8, 9, 0]

取序列开始的几个元素
>>> numbers[:3]
[1, 2, 15]

取序列所有元素
>>> numbers[:]
[1, 2, 15, 4, 5, 6, 7, 8, 9, 0]

步长指定

通过第三个参数来设定步长。

默认情况下步长为1,可以为负数。

>>> numbers[0:8]
[1, 2, 15, 4, 5, 6, 7, 8]
>>> numbers[0:8:2]
[1, 15, 5, 7]
>>> numbers[0:8:3]
[1, 4, 7]
#负数步长
>>> numbers[8:2:-2]
[9, 7, 5]

###加###

使用加号 + 可以把2个相同类型的序列相加

>>> [1,2,3] + [4,5,6]
[1, 2, 3, 4, 5, 6]
>>> str1 = 'test string 1'
>>> str2 = 'test result is ok'
>>> print str1 + ' ' + str2
test string 1 test result is ok
>>> str3 = str1 + ' ' + str2
>>> str3
'test string 1 test result is ok'
>>> str1 = str1 + ' is failed'
>>> str1
'test string 1 is failed'

###乘

如果一个序列乘以数字N,会生成一个新序列。

并且,新序列中会把原来的序列重复N次。 »> ‘python’*3 ‘pythonpythonpython’

经常用于列表初始化: »> sequence = [None]*5 »> sequence [None, None, None, None, None]

###in 运算符

判断一个值是否在序列中。条件为真返回True, 条件为假返回False.

>>> numbers
[1, 2, 15, 4, 5, 6, 7, 8, 9, 0]
>>> 15 in numbers
True
>>> 20 in numbers
False
>>> temp = [8]
>>> temp in numbers
False
>>> temp2 = [4,5,6,[8],[9]]
>>> temp2
[4, 5, 6, [8], [9]]
>>> temp in temp2
True

###序列长度, 最大元素, 最小元素

这3种运算主要使用3个内建函数: len, max, min。

>>> numbers
[1, 2, 15, 4, 5, 6, 7, 8, 9, 0]
>>> len(numbers)
10
>>> max(numbers)
15
>>> min(numbers)
0