將序列分解爲單獨的變量
>>> p = (4,5) # 通過賦值分解元組或序列
>>> x,y = p
>>> x
4
>>> y
5
>>> data = ['ACME', 50, 91.9, (2000,1,1)]
>>> name, shares, prices, date = data
>>> name
'ACME'
>>> date
(2000, 1, 1)
>>> name, shares, prices, (year, month, day) = data
>>> prices
91.9
>>> month
1
>>> day
1
>>> string = "hello" #只要對象是可迭代的,就可以進行分解操作
>>> a, b, c, d, e = string
>>> a
'h'
>>> b
'e'
>>> e
'o'
>>> name, _, prices, _ = data #_表示不感興趣的項
>>> name
'ACME'
>>> prices
91.9
>>> _
(2000, 1, 1)
>>> name, _, prices, _ , outbound= data # 解包元素不匹配
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
name, _, prices, _ , outbound= data
ValueError: need more than 4 values to unpack
從任意長度的可迭代對象中分解元素
>>> *trailing, current = [12, 23, 34, 45, 56, 67, 78, 89]
>>> current
89
>>> trailing # 使用“*表達式”進行分解匹配
[12, 23, 34, 45, 56, 67, 78]
>>> a, b, *, d = [12, 34, 45, 56, 67,89]
SyntaxError: invalid syntax
>>> a, b, *c, d = [12, 34, 45, 56, 67,89]
>>> a
12
>>> b
34
>>> c
[45, 56, 67]
>>> d
89
>>> line = 'nobody:*:-2:user:/home'
>>> uname, *others, path = line.split(':')
>>> uname
'nobody'
>>> path
'/home'
對於分解位置或者任意長度的可迭代對象,這樣再合適不過了。對於固定的組件或者模式(如,元素2以後的都是電話號碼,但是電話號碼的數量未知),使用星號表達式可以方便快捷的分解。
保存最後N個元素
#使用collections中的deque實現
from collections import deque
d = deque()
d.append('1')
d.append('2')
d.append('3')
len(d) # 3
d[0] # 1
d[-1] # 3
d = deque('12345')
len(d) # 5
d.popleft() # 1
d.pop() # 5
d # deque(['2', '3', '4'])
#我們還可以限制deque的長度:
d = deque(maxlen=30)
#當限制長度的deque增加超過限制數的項時, 另一邊的項會自動刪除:
d = deque(maxlen=2)
d.append(1)
d.append(2) # deque(['1', '2'])
d.append(3) # deque(['2', '3'])
| append(...)
| Add an element to the right side of the deque.
|
| appendleft(...)
| Add an element to the left side of the deque.
|
| clear(...)
| Remove all elements from the deque.
|
| count(...)
| D.count(value) -> integer -- return number of occurrences of value
|
| extend(...)
| Extend the right side of the deque with elements from the iterable
|
| extendleft(...)
| Extend the left side of the deque with elements from the iterable
|
| pop(...)
| Remove and return the rightmost element.
|
| popleft(...)
| Remove and return the leftmost element.
|
| remove(...)
| D.remove(value) -- remove first occurrence of value.
|
| reverse(...)
| D.reverse() -- reverse *IN PLACE*
|
| rotate(...)
| Rotate the deque n steps to the right (default n=1). If n is negative,
| rotates left.