序列
序列中的每个元素都有自己的编号,它的每一个元素都可以通过指定的偏移量得到。即其位置或索引。在python中第一个元素索引为0,并以此类推,最后一个元素索引为n-1。python中序列类型有:字符串,列表,元组。
一、序列类型操作符
1. 索引
In [1]: seq = 'hello'
In [2]: seq
Out[2]: 'hello'
In [3]: seq[2]
Out[3]: 'l'
In [4]: seq = [1,2,3,4,5]
In [5]: seq[2]
Out[5]: 3
2. 相加(连接)
In [6]: seq1 = 'hello'
In [7]: seq2 = 'world'
In [8]: seq1 + seq2
Out[8]: 'helloworld'
In [9]: [1,2,3] +[4,5,6]
Out[9]: [1, 2, 3, 4, 5, 6]
3. 乘法(重复)
In [10]: 'python' * 5
Out[10]: 'pythonpythonpythonpythonpython'
In [11]: [1,2,3] *3
Out[11]: [1, 2, 3, 1, 2, 3, 1, 2, 3]
4. 成员检查
in表示判断元素在序列中, not in表示判断元素不在序列中。返回True表示判断正确,返回False表示判断错误。
In [12]: 'a' in 'python'
Out[12]: False
In [13]: 'p' in 'python'
Out[13]: True
In [14]: p not in 'python'
Out[13]: True
In [15]: 'p' not in 'python'
Out[15]: False
In [17]: 5 in [1,2,3,4,5]
Out[17]: True
In [18]: 6 in [1,2,3,4,5]
Out[18]: False
5. 序列长度,最大值,最小值
In [22]: len('hello')
Out[22]: 5
In [23]: max('hello')
Out[23]: 'o'
In [24]: min('hello')
Out[24]: 'e'
In [25]: len([1,2,3,4,5])
Out[25]: 5
In [26]: max([1,2,3,4,5])
Out[26]: 5
In [27]: min([1,2,3,4,5])
Out[27]: 1
6. 切片
切片是用来访问特定范围内的元素,其形式为seq[start index:end index:step]
In [29]: a = [1,2,3,4,5,6,7,8,9]
In [30]: a[2:]
Out[30]: [3, 4, 5, 6, 7, 8, 9]
In [31]: a[:2]
Out[31]: [1, 2]
In [32]: a[2:8]
Out[32]: [3, 4, 5, 6, 7, 8]
In [33]: a[2:8:2]
Out[33]: [3, 5, 7]