序列(Sequences)主要包括列表(Lists)、元组(Tuple)和字符串(Strings),其中字符串和元组是不可修改的。
序列通用操作
定义
1 | ver = 'python3.6' |
索引访问
1 | ver[5] |
slice
1 | ver[0:6] |
concatenation
注意:不同数据类型不能拼接
1 | ver[:6] + '-' + ver[6:] |
repetition
1 | ver[:-1] + ver[-1:] * 2 |
是否存在
1 | '3' in ver |
长度、最小值、最大值
1 | len(ver) |
列表
定义
1 | ct = ['Peru', 'India', 'Japan', 'Iran'] |
修改
1 | ct[2] = 'Korea' |
删除
1 | del ct[1] |
分片赋值
1 | ct[2:] = ['Chain'] |
追加
1 | ct.append('America') |
count
1 | ct.count('Iran') |
list.extend(iterable)
等效于a[len(a):] = iterable
.
1 | ct.extend(['Egypt', 'Italy']) |
index
1 | ct.index('Peru') |
insert
1 | ct.insert(1, 'Canada') |
pop
1 | ct.pop() |
remove
1 | ct.remove('India') |
reverse
1 | ct.reverse() |
sort
1 | ct.sort() |
元组
定义
1 | fruit = ('apple', 'banana', 'mango') |
列表转换为元组
1 | tuple(['Perl', 'Python', 'Java']) |
分片
1 | fruit[1:] |
字典
字典是python中唯一内建的映射(mapping)类型
创建字典
1 | emails = { '163': 'xiongjiaxuans@163.com', 'google': 'xiongjiaxuans@gmail.com', 'microsoft': 'lanewf@live.com' } |
通过key访问
1 | emails['google'] |
长度
1 | len(emails) |
key是否存在
1 | '163' in emails |