問題:
給定一組資料對,它們對,它們分組基於指定索引處的值並將其轉換為所需的格式。
解決方案:
要按類型對資料有效分組,請按照以下步驟操作:
第1 步:建立字典
使用集合模組中的defaultdict 建立字典,其中鍵是類型,值是值列表:
<code class="python">from collections import defaultdict res = defaultdict(list) for v, k in input: res[k].append(v)</code>
第2 步:將字典轉換為所需格式
將建立的字典轉換為所需格式的字典清單:
<code class="python">result = [{'type': k, 'items': v} for k,v in res.items()]</code>
其他注意事項:
使用 **itertools.groupby()**:
另一種方法涉及使用itertools.groupby 函數,但需要對輸入資料進行排序terlebih dahulu。
<code class="python">import operator as itemgetter import itertools sorted_input = sorted(input, key=itemgetter(1)) groups = itertools.groupby(sorted_input, key=itemgetter(1)) result = [{'type': k, 'items':[x[0] for x in v]} for k, v in groups]</code>
以上是以下是一些標題選項,請記住問答格式以及本文的重點是在 Python 中將資料分組: 選項 1(一般): * 如何在Python中基於S對資料對進行分組的詳細內容。更多資訊請關注PHP中文網其他相關文章!