Python Cookbook (1-4) 內建演算法
1. Counter:
Counter 對 list 的元素進行計數,並可依照次數回傳前幾名的元素和該元素的次數。
from collections import Counter animals= ["dog", "dog", "dog", "cat", "bird", "bird"] animal_counts = Counter(animals) print(animal_counts) # Counter({'dog': 3, 'bird': 2, 'cat': 1}) print(animal_counts.most_common(2)) # [('dog', 3), ('bird', 2)] animal_counts.update(animals) # 追加一個 list print(animal_counts) # Counter({'dog': 6, 'bird': 4, 'cat': 2})
兩 Counter 的相互運算。
animals1= ["dog", "dog", "dog", "cat", "bird", "bird"] a = Counter(animals1) animals2= ["dog", "dog", "dog", "cat", "cat", "bird"] b = Counter(animals2) print(a + b) print(a - b)
2. sorted, min and max
假設我們想對 list of dict 的特定鍵進行排序或是找出最大最小。
animals = [{"name":"doggy", "age":10},{"name":"kitty", "age":3},{"name":"ducky", "age":4}] print(sorted(animals, key=lambda info: info["age"])) print(min(animals, key=lambda info: info["age"])) print(max(animals, key=lambda info: info["age"]))
另一種較快的方式是使用 itemgetter。
from operator import itemgetter print(sorted(animals, key=itemgetter("age"))
3. 對 class 進行排序
class student: def __init__(self, name, sid): self.name=name self.sid=sid def __repr__(self): return "{},{}".format(self.name, self.sid) lst = [student("alice", 3), student("bob", 1), student("cat", 2)] from operator import attrgetter sorted(lst, key=attrgetter("sid"))
也可將 attrgetter 用在 class 的 max 和 min 上。
4. groupby
將資料分群。
student = [{"name":"a", "class":1},{"name":"b", "class":2}, {"name":"c", "class":1}] from itertools import groupby from operator import itemgetter for k,g in groupby(student, key=itemgetter("class")): print(k) for item in g: print(item)
k,g 分別是 key 和群組的內容。
執行結果如下,如果要整齊一點要先對資料進行排序,因為是線性對元素進行群組操作。
1 {'name': 'a', 'class': 1} 2 {'name': 'b', 'class': 2} 1 {'name': 'c', 'class': 1}
先對資料進行排序,讓線性操作整齊一點(應該說都排序完也算分群完了)。
student = [{"name":"a", "class":1},{"name":"b", "class":2}, {"name":"c", "class":1}] from itertools import groupby from operator import itemgetter student.sort(key=itemgetter("class")) for k,g in groupby(student, key=itemgetter("class")): print(k) for item in g: print(item)
執行結果如下。
1 {'name': 'a', 'class': 1} {'name': 'c', 'class': 1} 2 {'name': 'b', 'class': 2}
5. filter
a = [i for i in range(10)] print(list(filter(lambda x: x%3 == 0, a))) # [0, 3, 6, 9]
Reference
[1] David Beazley, Brian K. Jones, Python Cookbook, 3e , O'Reilly Media (2014)
留言
張貼留言