揭秘Python的Itertools.groupby()
理解Itertools.groupby()的本質
理解Itertools.groupby()的本質>> 🎜>Itertools.groupby(),一個強大的Python函數,可讓您根據指定的標準將資料劃分為邏輯分組的元素。它需要兩個參數:要分組的資料和定義分組條件的關鍵函數。實作重點
有清除變數的範例名稱
from itertools import groupby things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")] for key, group in groupby(things, lambda x: x[0]): print(f"A {group[0]} is a {key}.")
輸出:
A bear is a animal. A duck is a animal. A cactus is a plant. A speed boat is a vehicle. A school bus is a vehicle.
資料排序的重要性
請注意,在某些情況下,您可能需要事先對資料進行排序以確保準確列表理解方法
使用列表理解的替代實現:for key, group in groupby(things, lambda x: x[0]): listOfThings = " and ".join([thing[1] for thing in group]) print(f"{key}s: {listOfThings}.")
輸出:
animals: bear and duck. plants: cactus. vehicles: speed boat and school bus.
以上是Python 的 itertools.groupby() 函數如何將資料分組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!