# coding=utf-8# 去掉第一名,最後一名,求平均值def avg(rest): return sum(rest) / rest.__len__()def drop_first_last(grades): first, *middle, last = grades return avg(middle)print (drop_first_last((99,2,3,4,5,6,7,8,1)))# 星號運算式在迭代元素為可變長元組的序列時是很有用的records = [ ('foo', 1, 2), ('bar', 'hello'), ('foo', 3, 4),]def do_foo(x, y): print('foo:', x, y)def do_bar(s): print('bar:', s)for tag, *args in records: if tag == 'foo': do_foo(*args) elif tag == 'bar': do_bar(*args)# 星號解壓文法在字串操作的時候也會很有用,比如字串的分割uname, *fields, homedir, sh = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false'.split(':')head, *tail = [1, 10, 7, 4, 5, 9]print(uname,homedir,sh)# 解壓一些元素後丟棄它們,你不能簡單就使用 * ,但是你可以使用一個普通的廢棄名稱,比如 或者 ignrecord = ('ACME', 50, 123.45, (12, 18, 2012))name, *_, (*_, year) = recordprint(name, year)# 在多行上面做簡單的文本匹配,並返回匹配所在行的前 N 行# 保留有限記錄正是 collections.deque 大顯身手的時候# deque 可以一直append, 大於5個後的append會擠出第一條from collections import dequedef search(lines, pattern, history=5): previous_lines = deque(maxlen=history) for li in lines: if pattern in li: yield li, previous_lines previous_lines.append(li)with open(r'test_api.py') as f: for line, prevlines in search(f, 'app_context', 5): for pline in prevlines: print(pline,) print(line,) print('-' * 20)# 一個集合中獲得最大或者最小的 N 個元素列表。# heapq 模組有兩個函數:nlargest() 和 nsmallest() 可以完美解決這個問題# 兩個函數都能接受一個關鍵字參數,用於更複雜的資料結構中:import heapqnums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]heapq.heapify(nums) #底層實現裡面,首先會先將集合資料進行堆排序後放入一個列表中print(heapq.nlargest(3, nums)) # Prints [42, 37, 23]print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]portfolio = [ {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}, {'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'ACME', 'shares': 75, 'price': 115.65}]print(heapq.nsmallest(3, portfolio, key=lambda s: s['price']))print(heapq.nlargest(3, portfolio, key=lambda s: s['price']))# 優先順序heapq隊列import heapqclass PriorityQueue: def __init__(self): self._queue = [] self._index = 0 def push(self, item, priority): heapq.heappush(self._queue, (-priority, self._index, item)) self._index += 1 def pop(self): return heapq.heappop(self._queue)[-1]class Item: def __init__(self, name): self.name = name def __repr__(self): return 'Item({!r})'.format(self.name)q = PriorityQueue()q.push(Item('foo'), 1)q.push(Item('bar'), 5)q.push(Item('spam'), 4)q.push(Item('grok'), 1)print(q.pop())print(q.pop())print(q.pop())print(q.pop())# 字典中的鍵映射多個值,# 使用 collections 模組中的 defaultdict 來構造這樣的字典,# 選擇使用列表還是集合取決於你的實際需求。如果你想保持元素的插入順序就應該# 使用列表,如果想去掉重複元素就使用集合(並且不關心元素的順序問題)。from collections import defaultdictd = defaultdict(list)d['a'].append(1)d['a'].append(2)d['a'].append(2)d['b'].append(4)dd = defaultdict(set)dd['a'].add(1)dd['a'].add(2)dd['a'].add(2)dd['b'].add(4)print(d, dd)# 字典的運算 (比如求最小值、最大值、排序等等)。prices = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75}min_price = min(zip(prices.values(), prices.keys()))max_price = max(zip(prices.values(), prices.keys()))prices_sorted = sorted(zip(prices.values(), prices.keys()))min(prices.values()) # Returns 10.75max(prices.values()) # Returns 612.78# 尋找兩字典的相同點# 以現有字典構造一個排除幾個指定鍵的新字典a = { 'x' : 1, 'y' : 2, 'z' : 3}b = { 'w' : 10, 'x' : 11, 'y' : 2}# Find keys in commona.keys() & b.keys() # { 'x', 'y' }# Find keys in a that are not in ba.keys() - b.keys() # { 'z' }# Find (key,value) pairs in commona.items() & b.items() # { ('y', 2) }# Make a new dictionary with certain keys removedc = {key:a[key] for key in a.keys() - {'z', 'w'}} # c is {'x': 1, 'y': 2}# 刪除序列相同元素並保持順序def dedupe(items): seen = set() for item in items: if item not in seen: yield item seen.add(item)# dict 類型def dedupefordict(items, key=None): seen = set() for item in items: val = item if key is None else key(item) if val not in seen: yield item seen.add(val)a = [1, 5, 2, 1, 9, 1, 5, 10]b = [{'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 1, 'y': 2}, {'x': 2, 'y': 4}]print(set(a)) # 產生的結果中的元素位置被打亂,以下方式可以解決print(list(dedupe(a)))print(list(dedupefordict(b, key=lambda d: (d['x'], d['y']))))print(list(dedupefordict(b, key=lambda d: d['x'])))# 1.12序列中出現次數最多的元素,Counter 對象實際就是一個字典,將元素映射到它出現的次數上from collections import Counterwords = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're", 'under']morewords = ['why', 'are', 'you', 'not', 'looking', 'in', 'my', 'eyes']word_counts = Counter(words)word_counts.update(morewords)top_three = word_counts.most_common(3) # 出現頻率最高的 3 個單詞print(top_three) # Outputs [('eyes', 8), ('the', 5), ('look', 4)]print(word_counts['not']) # 1print(word_counts['eyes']) # 8# 1.13 通過某個關鍵字排序一個字典列表