變量的數量要和序列中元素的數量相等。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]