- python中的序列类型主要有三种:字符、列表、元组
- 序列类型操作符
操作符 |
作用 |
成员关系符(in和not in) |
用来判断一个元素是否属于一个序列 |
连接操作符(+) |
把序列和另一个相同类型的序列做连接 |
重复操作符(*) |
将一个序列多次拷贝,格式-->sequence * copies_int |
切片操作符([],[:],[::]) |
返回一个切片列表 |
# 成员关系操作符 in/not in # 连接符 + -->只能连接相同对象,字符串,元组,字典
In [54]: list1 = ['a',1,'b',['x',2,3]] # 允许把多个序列连接在一起,但只能连接同样的对象;
In [55]: a in list1 In [64]: a = "abc"
Out[55]: False In [65]: b = "def"
In [56]: 'a' in list1 In [66]: a + b
Out[56]: True Out[66]: 'abcdef'
In [57]: 'x' in list1 In [67]: a = ['a','b','c']
Out[57]: False In [68]: b = ['d','e','f']
In [58]: 'x' in list1[3] In [69]: a + b
Out[58]: True Out[69]: ['a', 'b', 'c', 'd', 'e', 'f']
In [59]: list2 = "abcdefg" In [70]: a = ('a',1,'b')
In [60]: 'a' in list2 In [72]: b = ('c',2,'d')
Out[60]: True In [73]: a + b
In [61]: 'ad' not in list2 Out[73]: ('a', 1, 'b', 'c', 2, 'd')
Out[61]: True
In [62]: 'ab' in list2
Out[62]: True
# 重复操作符 * 后面只能跟数字
In [74]: a= "abc"
In [75]: a * 2
Out[75]: 'abcabc'
# 切片操作符
In [76]: lst = [1,2,3,4,5,6]
In [77]: exp = "abcdef"
In [78]: tub = ("apple","orange","banana","watermelon")
In [79]: print lst[2] -->3
In [81]: print exp[1] -->b
In [82]: print tub[2] -->banana
In [83]: print lst[-1] -->6
In [84]: print exp[:] -->abcdef
In [85]: print tub[:] -->('apple', 'orange', 'banana', 'watermelon')
In [86]: print lst[::-1] -->[6, 5, 4, 3, 2, 1]
In [87]: print lst[1:3] -->[2, 3]
In [88]: print lst[1:] -->[2, 3, 4, 5, 6]
In [89]: print lst[1:5:2] -->[2, 4]
In [90]: print lst[-5:-3] -->[2, 3]
In [91]: print exp[:-1] -->abcde
In [92]: print exp[2:4] -->cd
- 步长索引
- 语法:list[start:end:step]
- 若step>0,表示是从左向右进行切片;此时,start值必须小于end值才会有结果,否者为空;
- 若step<0,表示是从右向左进行切片;此时,start值必须大于end值才会有结果,否者为空;
- list[::-1]表示从右向左以步长为1进行切片
- list[::2]表示从左向右以步长为2进行切片
网友评论