>>> a = [1,2,3,4,5,6]
>>> a
[1, 2, 3, 4, 5, 6]
>>> a.clear() # 清除列表中的元素,但不会删除列表对象
>>> a
[]
>>> a = [1,2,3,4,5,6]
>>> del a # 删除列表对象
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> a = [3,5,6,4,1,9]
>>> a
[3, 5, 6, 4, 1, 9]
>>> a.index(5)
1
>>> a.index(1)
4
>>> a.index(1,4)
4
>>> a.index(1,5) # 为什么报错,因为索引是从第5个位置开始索引的
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 1 is not in list
>>> a.index(1,2,5)
4
>>> a.index(3,2,5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 3 is not in list
更新列表的值
可以对列表的数据项进行修改或更新
>>> a = [1,2,3,4]
>>> a[0] = 'angle'
>>> a
['angle', 2, 3, 4]
为列表进行排序
list.sort(key = None,reverse = False )
对列表中的项目进行排序(参数可用于排序自定义,请参阅sorted()其说明)
>>> a = [9,6,3,4,7,]
>>> a
[9, 6, 3, 4, 7]
>>> a.sort()
>>> a
[3, 4, 6, 7, 9]
# 利用key进行倒序排序
>>> a = [9,6,3,4,7,]
>>> a.sort(key=lambda x:-x)
>>> a
[9, 7, 6, 4, 3]
# 反向排序
>>> a = [9,6,3,4,7,]
>>> a.sort(reverse=True)
>>> a
[9, 7, 6, 4, 3]
list.reverse()
反转列表中的元素
>>> a
[9, 7, 6, 4, 3]
>>> a = [9,6,3,4,7,]
>>> a.reverse() # 这是反转列表,注意没有进行排序
>>> a
[7, 4, 3, 6, 9]
复制列表
list.copy()
返回列表的浅表副本。相当于a[:]
浅复制仅仅复制了容器中元素的地址
>>> a = [1,2,[3,4]]
>>> b = a.copy() # 浅拷贝:深拷贝父对象(一级目录),子对象(二级目录)不拷贝,还是引用
>>> c = a # 浅拷贝: 引用对象
>>> b
[1, 2, [3, 4]]
>>> a
[1, 2, [3, 4]]
>>> a[2]
[3, 4]
# 注意
>>> a[2].append(2)
>>> b
[1, 2, [3, 4, 2]]
>>> a.append(1)
# b[2]有新元素添加了,其余没变动
>>> b
[1, 2, [3, 4, 2]]
>>> a
[1, 2, [3, 4, 2], 1]
>>> c
[1, 2, [3, 4, 2], 1]
>>> from collections import deque
>>> d = deque('ghi') # make a new deque with three items
>>> for elem in d: # iterate over the deque's elements
... print(elem.upper())
G
H
I
>>> d.append('j') # add a new entry to the right side
>>> d.appendleft('f') # add a new entry to the left side
>>> d # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])
>>> d.pop() # return and remove the rightmost item
'j'
>>> d.popleft() # return and remove the leftmost item
'f'
>>> list(d) # list the contents of the deque
['g', 'h', 'i']
>>> d[0] # peek at leftmost item
'g'
>>> d[-1] # peek at rightmost item
'i'
>>> list(reversed(d)) # list the contents of a deque in reverse
['i', 'h', 'g']
>>> 'h' in d # search the deque
True
>>> d.extend('jkl') # add multiple elements at once
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> d.rotate(1) # right rotation
>>> d
deque(['l', 'g', 'h', 'i', 'j', 'k'])
>>> d.rotate(-1) # left rotation
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> deque(reversed(d)) # make a new deque in reverse order
deque(['l', 'k', 'j', 'i', 'h', 'g'])
>>> d.clear() # empty the deque
>>> d.pop() # cannot pop from an empty deque
Traceback (most recent call last):
File "<pyshell#6>", line 1, in -toplevel-
d.pop()
IndexError: pop from an empty deque
>>> d.extendleft('abc') # extendleft() reverses the input order
>>> d
deque(['c', 'b', 'a'])