Python中的 itertools.groupby()
先决条件: Python Itertools
Python 的 Itertool 是一个模块,它提供了在迭代器上工作以生成复杂迭代器的各种函数。该模块可作为一种快速、高效的内存工具,可单独使用或组合使用以形成迭代器代数。
Itertools.groupby()
此方法计算 iterable 中存在的每个元素的键。它返回分组项的键和可迭代项。
Syntax: itertools.groupby(iterable, key_func)
Parameters:
iterable: Iterable can be of any kind (list, tuple, dictionary).
key: A function that calculates keys for each element present in iterable.
Return type: It returns consecutive keys and groups from the iterable. If the key function is not specified or is None, key defaults to an identity function and returns the element unchanged.
示例 1:
# Python code to demonstrate
# itertools.groupby() method
import itertools
L = [("a", 1), ("a", 2), ("b", 3), ("b", 4)]
# Key function
key_func = lambda x: x[0]
for key, group in itertools.groupby(L, key_func):
print(key + " :", list(group))
输出:
a : [('a', 1), ('a', 2)]
b : [('b', 3), ('b', 4)]
示例 2:
# Python code to demonstrate
# itertools.groupby() method
import itertools
a_list = [("Animal", "cat"),
("Animal", "dog"),
("Bird", "peacock"),
("Bird", "pigeon")]
an_iterator = itertools.groupby(a_list, lambda x : x[0])
for key, group in an_iterator:
key_and_group = {key : list(group)}
print(key_and_group)
输出
{'Animal': [('Animal', 'cat'), ('Animal', 'dog')]}
{'Bird': [('Bird', 'peacock'), ('Bird', 'pigeon')]}