2015/8/30 Python基础(4):序列操作符

序列是指成员有序排列,可以通过下标偏移量访问的类型。Python序列包括:字符串、列表和元组。
序列的每个元素可以指定一个偏移量得到,多个元素是通过切片操作得到的。下标偏移量从0开始计数到总数-1结束。

序列类型操作符
这些操作符是对所有序列类型都适用的。

序列操作符  作用
seq[ind]  获得下标为ind的元素
seq[ind1:ind2]  获得下标从ind1到ind2的元素集合
seq * expr  序列重复expr次
seq1 + seq2  连接序列seq1和seq2
obj in seq  判断obj元素是否在seq中
obj not in seq  判断obj元素是否不再seq中

seq[ind]有下面这段代码

>>> lst = [1,2,3,4,5,6]
>>> exp = "abcdef"
>>> tub = ("apple","orange","banana","watermelon")
>>> print lst[2] #打印列表中下标为2的元素
3
>>> print exp[0] #三种序列的使用方式一致
a
>>> print tub[3]
watermelon
>>> print lst[-1]#负索引,以结束为起点
6
>>> print lst[6]#索引不能超出序列长度

Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
print lst[6]#索引不能超出序列长度
IndexError: list index out of range
>>> print [1,2,3,4,5,6][0] #可以不将序列赋值直接使用
1
>>> print 'abcde'[0] #可以不将序列赋值直接使用
a

上面涵盖了seq[ind]的几种使用方案。正索引的偏移数是 0 到(总元素数量-1),从首元素开始索引;负索引的偏移数是 -1 到 负的总元素数量,从尾元素开始索引。

但是这种索引方式只能索引一个元素,多个元素索引使用

sequence[start_index:end_index(:step)]

有如下代码

>>> lst = [1, 2, 3, 4, 5, 6]
>>> print lst[:] #省略两个坐标则从开始到结束
[1, 2, 3, 4, 5, 6]
>>> print lst[3:] #省略结束坐标
[4, 5, 6]
>>> print lst[:5] #省略开始坐标
[1, 2, 3, 4, 5]
>>> print lst[::2] #步长为2,隔一个取一个
[1, 3, 5]
>>> print lst[::-1] #反向序列
[6, 5, 4, 3, 2, 1]
>>> print lst[1:5:2] #从坐标1到坐标5之间,隔一个取一个
[2, 4]
>>> print lst[-5:-3]
[2, 3]
>>> print lst[-1:100]
[6]
>>> print lst[-6:-4] #负索引,并不负输出
[1, 2]
>>> print lst[-3:5] #正负索引同时存在时,坐标只代表位置,截取位置间的元素
[4, 5]
>>> print lst[:100] #索引可以超出序列长度
[1, 2, 3, 4, 5, 6]
>>> print lst[-5:100] #索引可以超出序列长度
[2, 3, 4, 5, 6]
关于切片运算,还有一个值得说的事,如果使用负索引:
>>> lst = [1,2,3,4,5,6,7]
>>> print lst[:-2]
[1, 2, 3, 4, 5]
>>> print lst[:-1]
[1, 2, 3, 4, 5, 6]
>>> print lst[:0]
[]

 当负索引是尾坐标时,我们永远无法截到最后一个元素,因为-1是负索引最大的值,如果使用0则会认为是正索引。

这种情况下,我们可以使用None来代替0的位置

>>> print lst[:None]
[1, 2, 3, 4, 5, 6, 7]

连接操作符 +

连接操作符允许把多个序列连在一起,但只能连接同样的对象。都是列表,都是字符串或都是元组

>>> num_lst = [1,2,3,4]
>>> mixup_lst = [567,'abc',[123,'aaa']]
>>> num_lst + mixup_lst
[1, 2, 3, 4, 567, 'abc', [123, 'aaa']]
>>> string = 'abcdef'
>>> num_lst + string

Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
num_lst + string
TypeError: can only concatenate list (not "str") to list

重复操作符(*)

>>> mixup_lst = [567,'abc',[123,'aaa']]
>>> string = 'abcdef'
>>> mixup_lst * 2
[567, 'abc', [123, 'aaa'], 567, 'abc', [123, 'aaa']]
>>> string * 3
'abcdefabcdefabcdef'
>>> mixup_lst * mixup_lst

Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
mixup_lst * mixup_lst
TypeError: can't multiply sequence by non-int of type 'list'

* 后只能接数字,代表重复次数,否则都会错误

成员关系操作 in , not in

>>> mixup_list = ['a',123,['x',1.4,35]]
>>> 'a' in mixup_list
True
>>> 'x' in mixup_list
False
>>> 'x' in mixup_list[2]
True
>>> string = 'abcdef'
>>> 'a' in string
True
>>> 'bcd' in string
True
>>> 'abd' in string
False

以上是in的几种操作,用于判别元素是否属于这个序列。如果使用not in 则结果相反。

原文地址:https://www.cnblogs.com/SRL-Southern/p/4771948.html