标签:app rac end remove ext strong module ack insert
1、创建
#方法一 L1 = [] #定义空列表 L2 = [‘a‘,‘b‘,‘c‘,‘d‘] #存4个值,索引为0-3 L3 = [‘abc‘,[‘def‘,‘ghi‘]] #嵌套列表 #方法二 L4 = list()
2、查询
>>> L2 = [‘a‘,‘b‘,‘c‘,‘d‘,‘a‘,‘e‘,1,2] >>> L2[2]#通过索引取值 ‘c‘ >>> L2[-1]#通过索引从列表右边开始取值 2 >>> L2[-2] 1 >>> L2.index(‘a‘)#返回指定元素的索引值,从左右查找,找到第一个匹配值,则返回 0 >>> L2.count(‘a‘)#统计指定元素的个数 2
3、切片
>>> L2 = [‘a‘,‘b‘,‘c‘,‘d‘,‘a‘,‘e‘,1,2] >>> L2[0:3]#返回从索引0至3的元素,不包括3,顾头不顾尾 [‘a‘, ‘b‘, ‘c‘] >>> L2[0:-1]#返回从索引0至最后一个值,不包括最后一个值 [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘a‘, ‘e‘, 1] >>> L2[3:6]#返回从索引3至6的元素 [‘d‘, ‘a‘, ‘e‘] >>> L2[3:]#返回从索引3至最后所有的值 [‘d‘, ‘a‘, ‘e‘, 1, 2] >>> L2[:3]#返回从0至3的值 [‘a‘, ‘b‘, ‘c‘] >>> L2[1:6:2]#返回索引1至6的值,但是步长为6(每隔一个值,取一个值) [‘b‘, ‘d‘, ‘e‘] >>> L2[:]#返回所有的值 [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘a‘, ‘e‘, 1, 2] >>> L2[::2]#按步长为2,返回所有的值 [‘a‘, ‘c‘, ‘a‘, 1]
4、增加
>>> L2 [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘a‘, ‘e‘, 1, 2] >>> L2.append(‘A‘)#列表最后面追加A >>> L2 [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘a‘, ‘e‘, 1, 2, ‘A‘] >>> L2.insert(3,‘B‘)#在列表的索引为3的位置,插入一个值B >>> L2 [‘a‘, ‘b‘, ‘c‘, ‘B‘, ‘d‘, ‘a‘, ‘e‘, 1, 2, ‘A‘]
5、修改
L2 [‘a‘, ‘b‘, ‘c‘, ‘B‘, ‘d‘, ‘a‘, ‘e‘, 1, 2, ‘A‘] >>> L2[3] = ‘Boy‘#把索引3的元素修改为Boy >>> L2 [‘a‘, ‘b‘, ‘c‘, ‘Boy‘, ‘d‘, ‘a‘, ‘e‘, 1, 2, ‘A‘] >>> L2[4:6] = ‘ALEX LI‘#把索引4-6的元素改为ALEX LI,不够元素自动增加 >>> L2 [‘a‘, ‘b‘, ‘c‘, ‘Boy‘, ‘A‘, ‘L‘, ‘E‘, ‘X‘, ‘ ‘, ‘L‘, ‘I‘, ‘e‘, 1, 2, ‘A‘]
6、删除
L2 [‘a‘, ‘b‘, ‘c‘, ‘Boy‘, ‘A‘, ‘L‘, ‘E‘, ‘X‘, ‘ ‘, ‘L‘, ‘I‘, ‘e‘, 1, 2, ‘A‘] >>> L2.pop()#删除最后一个元素 ‘A‘ >>> L2 [‘a‘, ‘b‘, ‘c‘, ‘Boy‘, ‘A‘, ‘L‘, ‘E‘, ‘X‘, ‘ ‘, ‘L‘, ‘I‘, ‘e‘, 1, 2] >>> L2.remove(‘L‘)#删除从左找到的第一个指定元素 >>> L2 [‘a‘, ‘b‘, ‘c‘, ‘Boy‘, ‘A‘, ‘E‘, ‘X‘, ‘ ‘, ‘L‘, ‘I‘, ‘e‘, 1, 2] >>> del L2[4]#用python的全局的删除方法删除指定元素 >>> L2 [‘a‘, ‘b‘, ‘c‘, ‘Boy‘, ‘E‘, ‘X‘, ‘ ‘, ‘L‘, ‘I‘, ‘e‘, 1, 2] >>> del L2[3:7]#删除多个元素 >>> L2 [‘a‘, ‘b‘, ‘c‘, ‘L‘, ‘I‘, ‘e‘, 1, 2]
7、循环
L2 = [‘a‘,‘b‘,‘c‘,‘d‘,‘a‘,‘e‘,1,2] for i in L2: print(i)
8、排序
>>> L2 = [‘a‘,‘b‘,‘A‘,‘C‘,‘#‘,‘!‘,1,2] >>> L2.sort() Traceback (most recent call last): File "<stdin>", line 1, in <module>#不能对包含了str和int的列表进行排序 TypeError: ‘<‘ not supported between instances of ‘int‘ and ‘str‘ >>> L2 = [‘a‘,‘b‘,‘A‘,‘C‘,‘#‘,‘!‘] >>> L2.sort() >>> L2 [‘!‘, ‘#‘, ‘A‘, ‘C‘, ‘a‘, ‘b‘] >>> L2.reverse()#反转 >>> L2 [‘b‘, ‘a‘, ‘C‘, ‘A‘, ‘#‘, ‘!‘]
9、其他
>>> L2 [‘b‘, ‘a‘, ‘C‘, ‘A‘, ‘#‘, ‘!‘] >>> L2.extend([1,2,3,4])#把一个列表,扩展到L2列表 >>> L2 [‘b‘, ‘a‘, ‘C‘, ‘A‘, ‘#‘, ‘!‘, 1, 2, 3, 4] >>> L2[2] = [‘Alex‘,‘Jack‘,‘Rain‘] >>> L2 [‘b‘, ‘a‘, [‘Alex‘, ‘Jack‘, ‘Rain‘], ‘A‘, ‘#‘, ‘!‘, 1, 2, 3, 4] >>> L2[2][2]#嵌套列表取值 ‘Rain‘ >>> L2.clear()#清空列表 >>> L2 [] >>> L2.copy()#后面详细分析
标签:app rac end remove ext strong module ack insert
原文地址:https://www.cnblogs.com/vettel2018/p/10022911.html