变量的数量要和序列中元素的数量相等。python
例子以下:
<!--more-->app
>>>x, y = (4,5) >>>x 4 >>>y 5 >>>a,_,(c,d) = [1,2,(3,4)] >>>a 1 >>>_ 2 >>>c 3 >>>d 4
不仅是元组与列表能够,任何可迭代对象均可以,包括字符串,文件,迭代器,生成器等。函数
能够用 _ 做为变量名,表示要丢弃的值。code
好比要取到序列中除去第一项和最后一项的值,求平均值。对象
def drop_first_last(grades): first, *middle, last = grades return avg(middle)
*arg 也能够放到第一个位置,事实上能够放到任何位置,表示剩余的全部值。队列
>>>from collections import deque >>>q = deque(1) >>>q = deque(2) >>>q = deque(3) >>>q deque([1,2,3]) >>>q.appendleft(4) >>>q deque([4,1,2,3]) >>>q.insert(0,8)#这种插入方法须要首先将列表中的全部元素向后移一个单位
heapq 模块中有两个函数 nlargest()和nsmallest()字符串
import heapq nums = [1, 2, 5, 34, -5, 42, -9] print(heapq.nlargest(3,nums))# Prints [42,34,5] print(heapq.nsmallest(3,nums))#Prints [-9,-5,1]