Python-List
Posted 徐李帅
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python-List相关的知识,希望对你有一定的参考价值。
1 切片:取多个元素 2 >>> names = ["A","B","C","D","E","F"] 3 >>> names[1:4] #取下标1至下标4之间的数字,包括1,不包括4 4 [‘B‘, C‘, ‘D‘] 5 >>> names[1:-1] #取下标1至-1的值,不包括-1 6 [‘B‘, ‘C‘, ‘D‘, ‘E‘] 7 >>> names[0:3] 8 [‘A‘, ‘B‘, ‘C‘] 9 >>> names[:3] #如果是从头开始取,0可以忽略,跟上句效果一样 10 [‘A‘, ‘B‘, ‘C‘] 11 >>> names[3:] #如果想取最后一个,必须不能写-1,只能这么写 12 [‘D‘, ‘E‘, ‘F‘] 13 >>> names[3:-1] #这样-1就不会被包含了 14 [‘D‘, ‘E‘] 15 >>> names[0::2] #后面的2是代表,每隔一个元素,就取一个 16 [‘A‘, ‘C‘, ‘E‘] 17 >>> names[::2] #和上句效果一样 18 [‘A‘, ‘C‘, ‘E‘] 19 20 追加 21 >>> names 22 [‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘] 23 >>> names.append(‘G‘) #在最后面插入值 24 [‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘, ‘G‘] 25 26 27 插入 28 >>> names 29 [‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘ , ‘G‘] 30 >>> names.insert(2,‘H‘) #在C前面插入H 31 [‘A‘, ‘B‘, ‘G‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘ , ‘G‘] 32 33 修改 34 >>> names 35 [‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘ , ‘G‘] 36 >>> names[2] = ‘H‘ #把下标2替换掉 37 [‘A‘, ‘B‘, ‘H‘, ‘D‘, ‘E‘, ‘F‘ , ‘G‘] 38 39 删除 40 >>> names 41 [‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘ , ‘G‘] 42 >>> del names[2] #把下标2删除掉 43 [‘A‘, ‘B‘, ‘D‘, ‘E‘, ‘F‘ , ‘G‘] 44 >>> names.remove(‘B‘) #删除指定元素 45 [‘A‘, ‘D‘, ‘E‘, ‘F‘ , ‘G‘] 46 >>> names.pop() #删除列表最后一个值 47 48 扩展 49 >>> names1 50 [‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘ , ‘G‘] 51 >>> names2 = [‘H‘,‘I‘,‘J‘] 52 >>> names1.extend(names2) 53 >>> names1 54 [‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘ , ‘G‘, ‘H‘, ‘I‘, ‘J‘] 55 56 拷贝 57 >>> names 58 [‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘ , ‘G‘] 59 >>> name_copy = names.copy() 60 >>> name_copy 61 [‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘ , ‘G‘] 62 63 统计 64 >>> names 65 [‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘ , ‘G‘, ‘C‘] 66 >>> names.count(‘C‘) 67 2 68 69 获取下标 70 >>> names 71 [‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘ , ‘G‘, ‘C‘] 72 >>> names.index(‘C‘) 73 2 74 75 排序&翻转 76 [‘Alex‘, ‘Amy‘, ‘Amy‘, ‘Tenglan‘, ‘Tom‘, ‘1‘, ‘2‘, ‘3‘] 77 >>> names.sort() #python3 里不同数据类型不能放在一起排序了 78 >>> names 79 [‘1‘, ‘2‘, ‘3‘, ‘Alex‘, ‘Amy‘, ‘Amy‘, ‘Tenglan‘, ‘Tom‘] 80 81 >>> names.reverse() #反转 82 >>> names 83 [‘Tom‘, ‘Tenglan‘, ‘Amy‘, ‘Amy‘, ‘Alex‘, ‘3‘, ‘2‘, ‘1‘]
以上是关于Python-List的主要内容,如果未能解决你的问题,请参考以下文章
python 来自https://mail.python.org/pipermail/python-list/2005-September/330478.html#Jean Brouwers