Python高级用法(一)

Author Avatar
patrickcty 2月 01, 2017

Python高级用法(一)

Python赋值方式可以有很多种,特别是对于可迭代变量,eg:list,tuple,字符串

一个list的内容赋值给多个变量

>>> list1 = ['this', 'is', 'a', 'list']
>>> a, *b, c = list1
>>> a
'this'
>>> b
['is', 'a']

Python对数据结构支持也不错

队列

>>> from collections import deque
>>> q = deque(maxlen=3)  # 容量为三的队列,多了就自动队头元素出队
>>> q.append(1)
>>> r = deque([1, 2, 3], maxlen=5)
>>> r.popleft()
1
>>> r.pop()
3


>>> import heapq
>>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
>>> heapq.nlargest(5, nums)  # 最大的五个
[42, 37, 23, 23, 18]
>>> heapq.nsmallest(5, nums)
[-4, 1, 2, 2, 7]
>>> heapq.heapify(nums)  # 进行堆排序,每次出堆的都是最小的
>>> nums
[-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8]
>>> headpq.headpop(nums)
-4