基础教程
数据结构
序列
序列是最基本的数据结构,元素位置即索引
+ 序列
+ 列表
可以修改
+ 元祖
不能修改 可以作为字典的键
+ 字符串
+ Unicode字符串
+ buffer对象
+ xrange对象
操作
索引
索引一般从0开始递增,当索引为负数时,会从最右边第一个元素开始计数,为-1,递减
‘hel’[-2] 输出’e’
索引可以来访问单个元素
分片
含义
访问一定范围内的元素
提取元素的第一个索引值:剩下部分的第一个索引值
>>> 'sdfgh'[1:3]
'df'
>>> 'sdfgh'[-3:0]
''
>>> 'sdfgh'[-3:]
'fgh'
>>> 'sdfgh'[:]
'sdfgh'
步长
通常隐式设置(1)
>>> [1,2,3,4,5,6][0:5:1]
[1, 2, 3, 4, 5]
>>> [1,2,3,4,5,6][0:5:2]
[1, 3, 5]
可以设置为负数,正数,但不能为0,如果是负数,将会从右向左开始提取元素
>>> [1,2,3,4,5,6][0:5:-2]
[]
>>> [1,2,3,4,5,6][5:0:-2]
[6, 4, 2]
序列相加(+)
前提前后元素必须是相同类型
>>> [0]+[2]
[0, 2]
>>> 'sss'+'rrr'
'sssrrr'
>>> [1,2]+'aa'
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
[1,2]+'aa'
TypeError: can only concatenate list (not "str") to list
乘法(*)
数据重复n次
>>> 'sws'*3
'swsswssws'
>>> [2,3,4]*2
[2, 3, 4, 2, 3, 4]
None在python中表示“什么都没有”
初始化长度为10的空列表
>>> q = [None]*10
>>> q
[None, None, None, None, None, None, None, None, None, None]
成员资格(in)
>>> 'a' in 'asd'
True
>>> 'a' in 'ww'
False
长度len 最小值min 最大值max
列表
list函数
将其他类型数据转换成列表
>>> list('qwe')
['q', 'w', 'e']