将序列分解为单独的变量
>>> 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.
时间: 2024-09-30 18:32:35