列表
从列表中删除元素
1. 使用del 语句删除元素
使用del 可删除任何位置处的列表元素,条件是知道其索引。
names=["thompson","curry","bogute"]
print(names)
del names[2]
['thompson', 'curry', 'bogute']
['thompson', 'curry']
2. 使用方法pop() 删除元素
方法pop() 可删除列表末尾的元素,并让你能够接着使用它。术语弹出 (pop)源自这样的类比:列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素。
1 names=["thompson","curry","bogute"] 2 print(names) 3 poped_names=names.pop() 4 print(names) 5 print(poped_names)
['thompson', 'curry', 'bogute']
['thompson', 'curry']
bogute
3. 可以使用pop() 来删除列表中任何位置的元素,只需在括号中指定要删除的元素的索引即可。
names=["thompson","curry","bogute","green"]
print(names)
poped_names=names.pop(2)
print(names)
print(poped_names)
['thompson', 'curry', 'bogute', 'green']
['thompson', 'curry', 'green']
bogute
4. 根据值删除元素
有时候,你不知道要从列表中删除的值所处的位置。如果你只知道要删除的元素的值,可使用方法remove()
1 names=["thompson","curry","bogute","green"] 2 print(names) 3 names.remove("bogute") 4 print(names)
['thompson', 'curry', 'bogute', 'green']
['thompson', 'curry', 'green']
注意 方法remove() 只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有这样的值。
在列表末尾添加元素
1. 在列表末尾添加元素
names=["thompson","curry","green"] print(names) names.append("durant") print(names)
['thompson', 'curry', 'green']
['thompson', 'curry', 'green', 'durant']
2. 在列表中插入元素
使用方法insert() 可在列表的任何位置添加新元素。为此,你需要指定新元素的索引和值。
1 names=["thompson","curry","green"] 2 print(names) 3 names.append("durant") 4 print(names) 5 names.insert(2,"iguodala") 6 print(names)
['thompson', 'curry', 'green']
['thompson', 'curry', 'green', 'durant']
['thompson', 'curry', 'iguodala', 'green', 'durant']
使用方法sort() 对列表进行永久性排序
方法sort() 永久性地修改了列表元素的排列顺序
abc=["d","f","g","e","a","q","j","m","s","c","u","z",] print(abc) abc.sort() print(abc)
['d', 'f', 'g', 'e', 'a', 'q', 'j', 'm', 's', 'c', 'u', 'z']
['a', 'c', 'd', 'e', 'f', 'g', 'j', 'm', 'q', 's', 'u', 'z']
还可以按与字母顺序相反的顺序排列列表元素,为此,只需向sort() 方法传递参数reverse=True 。
abc=["d","f","g","e","a","q","j","m","s","c","u","z",] print(abc) abc.sort(reverse=True) print(abc)
['d', 'f', 'g', 'e', 'a', 'q', 'j', 'm', 's', 'c', 'u', 'z']
['z', 'u', 's', 'q', 'm', 'j', 'g', 'f', 'e', 'd', 'c', 'a']
使用函数sorted() 对列表进行临时排序
abc=["d","f","g","e","a","q","j","m","s","c","u","z",] print(abc) print(sorted(abc)) print(sorted(abc,reverse=True)) print(abc )
['d', 'f', 'g', 'e', 'a', 'q', 'j', 'm', 's', 'c', 'u', 'z']
['a', 'c', 'd', 'e', 'f', 'g', 'j', 'm', 'q', 's', 'u', 'z']
['z', 'u', 's', 'q', 'm', 'j', 'g', 'f', 'e', 'd', 'c', 'a']
['d', 'f', 'g', 'e', 'a', 'q', 'j', 'm', 's', 'c', 'u', 'z']
倒着打印列表方法reverse()
reverse() 不是指按与字母顺序相反的顺序排列列表元素,而只是反转列表元素的排列顺序 方法reverse() 永久性地修改列表元素的排列顺序,但可随时恢复到原来的排列顺序,为此只需对列表再次调用reverse() 即可。
abc=["d","f","g","e","a","q","j","m","s","c","u","z",] print(abc) abc.reverse() print(abc)
['d', 'f', 'g', 'e', 'a', 'q', 'j', 'm', 's', 'c', 'u', 'z']
['z', 'u', 'c', 's', 'm', 'j', 'q', 'a', 'e', 'g', 'f', 'd']
函数len() 可快速获悉列表的长度。
abc=["d","f","g","e","a","q","j","m","s","c","u","z",] print(len(abc))
12
访问列表中的元素,输出所有元素
names=["thompson","curry","green","durant","igoudala"] for name in names: print(name)
thompson
curry
green
durant
igoudala