序列类型
序列表示索引为非负整数的有序对象集合,包括字符串,列表,元祖。
字符串是字符的序列,列表和元祖是任意python对象的序列。
字符串和元祖不可变,列表可以插入,删除和替换元素,是可变的。
所有序列都支持迭代
序列的通用操作和方法
- 索引
s[i]
>>> s = "123456"
>>> s[5]
'6'
- 切片
s[i:j]
s[i:j:stride]
>>> l = ["a","b","c",'d','e']
>>> l[1:5]
['b', 'c', 'd', 'e']
>>> l[1:5:2]
['b', 'd']
>>> l[-1::-1]
['e', 'd', 'c', 'b', 'a']
- 元素个数
len(s)
>>> l = ["a","b","c",'d','e']
>>> len(l)
5
- 最小值,最大值(元素的数据类型要相同)
min(s)
max(s)
>>> t = ("3","4","6","a","g","3")
>>> max(t)
'g'
>>> min(t)
'3'
- 求和(元素为数字类型)
sum(s,[,initial])
>>> t = (1,2,3,4,5,6,7,8,9)
>>> sum(t)
45
>>> sum(t,1)
46
- 检查所有项是否为True
all(s)
>>> l = [1,"a",""]
>>> all(l)
False
- 检查至少有一项是True
any(s)
>>> l = [1,"a",""]
>>> any(l)
True