happy_boy 发表于 2015-11-30 12:06:05

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

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




序列操作符
作用


seq
获得下标为ind的元素


seq
获得下标从ind1到ind2的元素集合


seq * expr
序列重复expr次


seq1 + seq2
连接序列seq1和seq2


obj in seq
判断obj元素是否在seq中


obj not in seq
判断obj元素是否不再seq中


  
  seq有下面这段代码



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

Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
print lst#索引不能超出序列长度
IndexError: list index out of range
>>> print #可以不将序列赋值直接使用
1
>>> print 'abcde' #可以不将序列赋值直接使用
a
  上面涵盖了seq的几种使用方案。正索引的偏移数是 0 到(总元素数量-1),从首元素开始索引;负索引的偏移数是 -1 到 负的总元素数量,从尾元素开始索引。
  但是这种索引方式只能索引一个元素,多个元素索引使用



sequence
  
  有如下代码



>>> lst =
>>> print lst[:] #省略两个坐标则从开始到结束

>>> print lst #省略结束坐标

>>> print lst[:5] #省略开始坐标

>>> print lst[::2] #步长为2,隔一个取一个

>>> print lst[::-1] #反向序列

>>> print lst #从坐标1到坐标5之间,隔一个取一个

>>> print lst[-5:-3]

>>> print lst[-1:100]

>>> print lst[-6:-4] #负索引,并不负输出

>>> print lst[-3:5] #正负索引同时存在时,坐标只代表位置,截取位置间的元素

>>> print lst[:100] #索引可以超出序列长度

>>> print lst[-5:100] #索引可以超出序列长度


关于切片运算,还有一个值得说的事,如果使用负索引:


>>> lst =
>>> print lst[:-2]

>>> print lst[:-1]

>>> print lst[:0]
[]
  当负索引是尾坐标时,我们永远无法截到最后一个元素,因为-1是负索引最大的值,如果使用0则会认为是正索引。
  这种情况下,我们可以使用None来代替0的位置



>>> print lst[:None]

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



>>> num_lst =
>>> mixup_lst = ]
>>> num_lst + mixup_lst
]
>>> 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 = ]
>>> string = 'abcdef'
>>> mixup_lst * 2
, 567, 'abc', ]
>>> 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
True
>>> string = 'abcdef'
>>> 'a' in string
True
>>> 'bcd' in string
True
>>> 'abd' in string
False
  以上是in的几种操作,用于判别元素是否属于这个序列。如果使用not in 则结果相反。
页: [1]
查看完整版本: 2015/8/30 Python基础(4):序列操作符