python进阶(数据结构和算法[1])

将序列分解为单独的变量>>> p = (4,5) # 通过赋值分解元组或序列>>> x,y = p>>> x4>>> y5>>> 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>>> prices91.9>>> month1>>> daya, b, c, d, e = string>>> a’h’>>> b’e’>>> ename’ACME’>>> prices91.9>>> _(2000, 1, 1)>>> name, _, prices, _ , outbound= data # 解包元素不匹配Traceback (most recent call last): File “<pyshell#38>”, line 1, in <module>name, _, prices, _ , outbound= dataValueError: need more than 4 values to unpack从任意长度的可迭代对象中分解元素>>> *trailing, current = [12, 23, 34, 45, 56, 67, 78, 89]>>> current89>>> 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]>>> a12>>> b34>>> c[45, 56, 67]>>> duname, *others, path = line.split(‘:’)>>> uname’nobody’>>> path’/home’

对于分解位置或者任意长度的可迭代对象,这样再合适不过了。对于固定的组件或者模式(如,元素2以后的都是电话号码,但是电话号码的数量未知),使用星号表达式可以方便快捷的分解。

保存最后N个元素#使用collections中的deque实现from collections import dequed = deque()d.append(‘1’)d.append(‘2’)d.append(‘3’)len(d) # 3d[0] # 1d[-1] # 3d = deque(‘12345’)len(d) # 5d.popleft() # 1d.pop() # 5d # 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.

,接受失败,是我们不常听到或看到的一个命题,我们大都接受的是正面的教育,

python进阶(数据结构和算法[1])

相关文章:

你感兴趣的文章:

标签云: