序列类型(Sequence Types)
序列类型包括:list, tuple, range, 补充:字符串类型,二进制数据类型(binary data)
其中包括可变序列类型:如list,不可变序列类型: 如字符串类型,tuple类型
可变序列类型操作
1. 列表
序列类型共有操作:索引取值,索引切片,for循环取值,成员运算,index查找索引位置, len 长度, “+”运算
增加元素:append, expand, insert
删除元素:pop, del, remove, clear
排序相关:sort, reverse
lst = [0 for i in range(10)]
lst
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
lst[:5] = range(1,6)
lst
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
lst *= 2
lst
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
lst.pop(0)
lst
[2, 3, 4, 5, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
[func for func in dir(lst) if not func.startswith("__")]
['append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']
不可变序列类型操作
字符串
[func for func in dir("str") if not func.startswith("__")]
['capitalize',
'casefold',
'center',
'count',
'encode',
'endswith',
'expandtabs',
'find',
'format',
'format_map',
'index',
'isalnum',
'isalpha',
'isascii',
'isdecimal',
'isdigit',
'isidentifier',
'islower',
'isnumeric',
'isprintable',
'isspace',
'istitle',
'isupper',
'join',
'ljust',
'lower',
'lstrip',
'maketrans',
'partition',
'replace',
'rfind',
'rindex',
'rjust',
'rpartition',
'rsplit',
'rstrip',
'split',
'splitlines',
'startswith',
'strip',
'swapcase',
'title',
'translate',
'upper',
'zfill']
序列类型共有操作:索引取值,索引切片,for循环取值,成员运算,index查找索引位置, len 长度, “+”运算
缩短字符:strip, lstrip, rstrip
增加字符:center, ljust, rjust, zfill
切分和连接:split (rsplit), join, splitlines
转换或替代:upper, lower, swapcase, title, capitalize, replace, translate
判断:isdigit, isalpha, startswith, endswith ...
字典
[func for func in dir(dict) if not func.startswith("__")]
['clear',
'copy',
'fromkeys',
'get',
'items',
'keys',
'pop',
'popitem',
'setdefault',
'update',
'values']
定义字典
d = {"a":"abc", "b":"bcd"}
d = dict(a="abc", b="bcd")
d = dict.fromkeys("ab", "default")
d
{'a': 'default', 'b': 'default'}
增加元素相关的方法: setdefault, update
删除元素相关的方法: del, pop, popitem, clear
查询相关方法: get, items, keys, values
d.update(a=123)
d
{'a': 123, 'b': 'default'}
d.update(e=456789)
d
{'a': 123, 'b': 'default', 'e': 456789}
d.setdefault("c", 4567)
4567
d
{'a': 123, 'b': 'default', 'e': 456789, 'c': 4567}
元组
[func for func in dir(tuple) if not func.startswith("__")]
['count', 'index']
具有序列类型数据共有操作
集合
[func for func in dir(set) if not func.startswith("__")]
['add',
'clear',
'copy',
'difference',
'difference_update',
'discard',
'intersection',
'intersection_update',
'isdisjoint',
'issubset',
'issuperset',
'pop',
'remove',
'symmetric_difference',
'symmetric_difference_update',
'union',
'update']
help(set.difference_update)
Help on method_descriptor:
difference_update(...)
Remove all elements of another set from this set.
#### 集合操作相关运算
a = {1, 2, 3, 4}
b = {2,3,5,6}
a | b # 并集
{1, 2, 3, 4, 5, 6}
a & b # 交集
{2, 3}
a ^ b
{1, 4, 5, 6}
a - b # 差集
{1, 4}