查询格式为:
list[起始位置:结束位置:步长]list特点为顾头不顾腚,包含开头不包含结尾步长默认为正序,步长1;可修改如:1,2,3......步长也可为负数,则查询结果为倒序如:-1,-2,-3.....正序时,起始和结束也为正序,起始在前结束在后倒序时,起始和结束也需为倒序,起始在后结束在前倒序+步长
lis1 = ['a','b','c','d','e','f']>>> lis1[::-1]['f', 'e', 'd', 'c', 'b', 'a']>>> lis1[-1:0:-1]['f', 'e', 'd', 'c', 'b']>>> lis1[::2]['a', 'c', 'e']
添加元素
lis1 = ['a','b','c','d','e','f']lis1.append("g")>>> lis1['a', 'b', 'c', 'd', 'e', 'f', 'g']
删除元素
lis1 = ['a','b','c','d','e','f','g']>>> li = lis1.pop()>>> li'g'>>> lis1['a', 'b', 'c', 'd', 'e', 'f']
>>> lis1 = ['a','b','c','d','e','f']
>>> del lis1[0]>>> lis1['b', 'c', 'd', 'e', 'f']>>> lis1 = ['a','b','c','d','e','f']>>> lis1.remove("f")>>> lis1['a', 'b', 'c', 'd', 'e']插入元素
lis1 = ['a','b','c','d','e','f']>>> lis1.insert(0,"y")>>> lis1['y', 'a', 'b', 'c', 'd', 'e', 'f']
出现次数+出现位置
>>> lis2 = ['a','b','a','a','b','c']>>> lis2.count('a')3>>> lis2.count('b')2>>> lis2.index("b")1>>> lis2.index('b',2)4>>> lis2.index('c')5
排序+倒序
>>> lis3 = [3,5,1,8,2,4,6,3]>>> lis3.sort()>>> lis3[1, 2, 3, 3, 4, 5, 6, 8]>>> lis3.sort(reverse=-1)>>> lis3[8, 6, 5, 4, 3, 3, 2, 1]
扩展列表
>>> lis3 = [3,5,1,8,2,4,6,3]>>> lis3[len(lis3):]=["a","b","c"]>>> lis3[8, 6, 5, 4, 3, 3, 2, 1, 'a', 'b', 'c']>>> lis3.extend(['d','e','f'])>>> lis3[8, 6, 5, 4, 3, 3, 2, 1, 'a', 'b', 'c', 'd', 'e', 'f']
去重
>>> l1 = ['b','c','d','b','c','a','a']>>> l2 = list(set(l1))>>> l2['c', 'b', 'a', 'd']>>> l2=list(set(l1))>>> l2.sort(key=l1.index)#去重后顺序不变>>> l2['b', 'c', 'd', 'a']>>> l1['b', 'c', 'd', 'b', 'c', 'a', 'a']>>> l2=list({}.fromkeys(l1).keys())>>> l2['b', 'c', 'd', 'a']>>> l1['b', 'c', 'd', 'b', 'c', 'a', 'a']>>> l2=[]>>> for i in l1: if not i in l2: l2.append(i)>>> l2['b', 'c', 'd', 'a']>>> l1['b', 'c', 'd', 'b', 'c', 'a', 'a']>>> l2 = []>>> [l2.append(i) for i in l1 if not i in l2][None, None, None, None]>>> l2['b', 'c', 'd', 'a']
多重赋值
>>> cat =['fat','black','loud']>>> size = cat[0]>>> color = cat[1]>>> disposition = cat[2]>>> cat =['fat','black','loud']>>> size,color,disposition = cat