数据类型——列表
如何通过一个变量存储公司所有员工的名字?
列表是一个数据的集合,集合内可以放任何数据类型,可对集合进行方便的增删改查操作。
列表的功能:
#方法一
L1 = [] #定义空列表 L2 = [‘a‘,‘b‘,‘c‘,‘d‘] #存4个值,索引为0-3 L3 =[‘abc‘,[‘def‘,‘ghi‘]] #嵌套列表
#方法二
L4 = list()
>>> >>> L2 = [‘a‘,‘b‘,‘c‘,‘d‘,‘a‘,‘e‘,1,2] >>> L2[2] #通过索引取值 ‘c‘ >>> L2[-1]#通过索引从列表右边开始取值 2 >>> L2.index(‘a‘) #返回指定元素的索引值,从左向右查找,找到第一个匹配值 0 >>> L2.count(‘a‘) #统计指定元素的个数 2 >>>
>>> L1 =[‘shanshan‘,‘longting‘,‘alex‘,1,34,4,5,6,9,2,1,1,5,8,8,10] >>> L1[0:2] [‘shanshan‘, ‘longting‘] >>> L1[3:7] [1, 34, 4, 5] >>> L1[-5:-1] #切片只能从左向右切 [1, 5, 8, 8] >>> L1[-5:] #切片顾头不顾尾,要切到最后,就冒号后什么都不写 [1, 5, 8, 8, 10] >>> L1[:3] [‘shanshan‘, ‘longting‘, ‘alex‘] >>> L1[:] [‘shanshan‘, ‘longting‘, ‘alex‘, 1, 34, 4, 5, 6, 9, 2, 1, 1, 5, 8, 8, 10] >>> L1[:7:2] [‘shanshan‘, ‘alex‘, 34, 5] >>> L1[:7:3] [‘shanshan‘, 1, 5] >>> L1[::2] [‘shanshan‘, ‘alex‘, 34, 5, 9, 1, 5, 8]
>>> n2 = [‘shanshan‘,‘Longting‘,‘Alex‘,1,3,4,5,65,22,4,1,444,67] >>> n2.append(‘peiqi‘) >>> n2 [‘shanshan‘, ‘Longting‘, ‘Alex‘, 1, 3, 4, 5, 65, 22, 4, 1, 444, 67, ‘peiqi‘] >>> n2.insert(0,‘abc‘) >>> n2 [‘abc‘, ‘shanshan‘, ‘Longting‘, ‘Alex‘, 1, 3, 4, 5, 65, 22, 4, 1, 444, 67, ‘peiq i‘] >>> n2.insert(2,‘James‘) >>> n2 [‘abc‘, ‘shanshan‘, ‘James‘, ‘Longting‘, ‘Alex‘, 1, 3, 4, 5, 65, 22, 4, 1, 444, 67, ‘peiqi‘] >>>
>>> n2 [‘abc‘, ‘shanshan‘, ‘James‘, ‘Longting‘, ‘Alex‘, 1, 3, 4, 5, 65, 22, 4, 1, 444, 67, ‘peiqi‘] >>> n2[2]=‘TTT‘ >>> n2 [‘abc‘, ‘shanshan‘, ‘TTT‘, ‘Longting‘, ‘Alex‘, 1, 3, 4, 5, 65, 22, 4, 1, 444, 67 , ‘peiqi‘] >>> n2[2:5]=[‘Jake‘,‘ti‘] >>> n2 [‘abc‘, ‘shanshan‘, ‘Jake‘, ‘ti‘, 1, 3, 4, 5, 65, 22, 4, 1, 444, 67, ‘peiqi‘] >>>
>>> n2 = [‘shanshan‘,‘Longting‘,‘Alex‘,1,3,4,5,65,22,4,1,444,67] >>> n2.pop() 67 >>> n2 [‘shanshan‘, ‘Longting‘, ‘Alex‘, 1, 3, 4, 5, 65, 22, 4, 1, 444] >>> #pop是删除列表的最后一项,并返回这项的值 >>> n2.remove(1) >>> n2 [‘shanshan‘, ‘Longting‘, ‘Alex‘, 3, 4, 5, 65, 22, 4, 1, 444] >>> del n2[2] >>> n2 [‘shanshan‘, ‘Longting‘, 3, 4, 5, 65, 22, 4, 1, 444] >>> n2 [‘shanshan‘, ‘Longting‘, 3, 4, 5, 65, 22, 4, 1, 444] >>> del n2[2:5] >>> n2 [‘shanshan‘, ‘Longting‘, 65, 22, 4, 1, 444]
>>> for k in n2: ... print(‘loop:‘,k) ... loop: shanshan loop: Longting loop: 65 loop: 22 loop: 4 loop: 1 loop: 444 >>> for i in range(0,10): ... print(i) ... 0 1 2 3 4 5 6 7 8 9
>>> n [‘a‘, ‘y‘, ‘e‘, ‘A‘, ‘b‘, ‘c‘, ‘z‘] >>> n.sort() >>> n [‘A‘, ‘a‘, ‘b‘, ‘c‘, ‘e‘, ‘y‘, ‘z‘] >>> n.reverse() >>> n [‘z‘, ‘y‘, ‘e‘, ‘c‘, ‘b‘, ‘a‘, ‘A‘]
列表拼接:
>>> n2 [1, 3, 4] >>> n [‘z‘, ‘y‘, ‘e‘, ‘c‘, ‘b‘, ‘a‘, ‘A‘] >>> n2+n [1, 3, 4, ‘z‘, ‘y‘, ‘e‘, ‘c‘, ‘b‘, ‘a‘, ‘A‘] >>> n2.extend(n) >>> n2 [1, 3, 4, ‘z‘, ‘y‘, ‘e‘, ‘c‘, ‘b‘, ‘a‘, ‘A‘] >>>
清空列表
>>> n2 [1, 3, 4, ‘z‘, ‘y‘, ‘e‘, ‘c‘, ‘b‘, ‘a‘, ‘A‘] >>> >>> n2.clear() >>> n2 []
copy
>>> n=[1,2,4,7,2] >>> n [1, 2, 4, 7, 2] >>> n1=n.copy() >>> n1 [1, 2, 4, 7, 2] >>> n.pop() 2 >>> n [1, 2, 4, 7] >>> n1 [1, 2, 4, 7, 2]
原文:https://www.cnblogs.com/echo-kid-coding/p/11148093.html