首頁  >  文章  >  後端開發  >  以下是一些標題選項,請記住問答格式以及本文的重點是在 Python 中將資料分組: 選項 1(一般): * 如何在Python中基於S對資料對進行分組

以下是一些標題選項,請記住問答格式以及本文的重點是在 Python 中將資料分組: 選項 1(一般): * 如何在Python中基於S對資料對進行分組

DDD
DDD原創
2024-10-27 09:04:30820瀏覽

Here are a few title options, keeping in mind the question-answer format and the article's focus on grouping data pairs in Python:

Option 1 (General):

* How to Group Data Pairs in Python Based on Specific Indices?

Option 2 (Specific to the Solution):

Python Group By

問題:

給定一組資料對,它們對,它們分組基於指定索引處的值並將其轉換為所需的格式。

解決方案:

要按類型對資料有效分組,請按照以下步驟操作:

第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>

其他注意事項:

  • 要在3.7 之前的Python 版本中保留鍵的原始順序,請使用集合模組中的OrderedDict。
  • 對於 Python 3.7 版本及以上,常規字典維護插入順序。

使用 **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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn