Python Group By
人們可能會遇到需要按每對中的第二個元素對一組資料分組,同時將第一個元素保留為清單的情況分組結果。這可以在 Python 中使用以下步驟有效地實現。
使用字典
使用集合模組中的 defaultdict 建立一個字典,其中鍵是該對的第二個元素。然後,迭代輸入列表並將第一個元素附加到對應鍵的值。
<code class="python">import collections input = [ ('11013331', 'KAT'), ('9085267', 'NOT'), ('5238761', 'ETH'), ('5349618', 'ETH'), ('11788544', 'NOT'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('9843236', 'KAT'), ('5594916', 'ETH'), ('1550003', 'ETH'), ] res = collections.defaultdict(list) for v, k in input: res[k].append(v)</code>
使用列表理解將字典轉換為預期的JSON 格式:
<code class="python">result = [{'type': k, 'items': v} for k, v in res.items()]</code>
使用itertools.groupby
另一種方法涉及使用itertools.groupby,groupby
<code class="python">from operator import itemgetter from itertools import groupby sorted_input = sorted(input, key=itemgetter(1)) groups = groupby(sorted_input, key=itemgetter(1))</code>另一種方法涉及使用itertools.groupby,groupby但要求輸入清單依第二個元素排序。
<code class="python">result = [{'type': k, 'items': [x[0] for x in v]} for k, v in groups]</code>使用推導式建立字典清單:
Python 版本注意事項
<code class="python">from collections import OrderedDict res = OrderedDict() for v, k in input: if k in res: res[k].append(v) else: res[k] = [v]</code>Python 3.7 之前,不保留字典中鍵的順序。若要保持原始順序,請使用 collections.OrderedDict。 從 Python 3.7 開始,常規字典會保持插入順序,因此不再需要 OrderedDict。
以上是如何以每對的第二個元素對 Python 中的對清單進行有效分組,同時將第一個元素保留為分組結果中的清單?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增強效率和通用性。

theKeyDifferencesBetnewpython's“ for”和“ for”和“ loopsare:1)” for“ loopsareIdealForiteringSequenceSquencesSorkNowniterations,而2)”,而“ loopsareBetterforConterContinuingUntilacTientInditionIntionismetismetistismetistwithOutpredefinedInedIterations.un

在Python中,可以通過多種方法連接列表並管理重複元素:1)使用 運算符或extend()方法可以保留所有重複元素;2)轉換為集合再轉回列表可以去除所有重複元素,但會丟失原有順序;3)使用循環或列表推導式結合集合可以去除重複元素並保持原有順序。

fasteStmethodMethodMethodConcatenationInpythondependersonListsize:1)forsmalllists,operatorseffited.2)forlargerlists,list.extend.extend()orlistComprechensionfaster,withextendEffaster,withExtendEffers,withextend()withextend()是extextend()asmoremory-ememory-emmoremory-emmoremory-emmodifyinginglistsin-place-place-place。

toInSerteLementIntoApythonList,useAppend()toaddtotheend,insert()foreSpificPosition,andextend()formultiplelements.1)useappend()foraddingsingleitemstotheend.2)useAddingsingLeitemStotheend.2)useeapecificindex,toadapecificindex,toadaSpecificIndex,toadaSpecificIndex,blyit'ssssssslorist.3 toaddextext.3

pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)他們areStoredIncoNtiguulMemoryBlocks,mayrequireRealLealLocationWhenAppendingItems,EmpactingPerformance.2)LinkesedlistSwoldOfferefeRefeRefeRefeRefficeInsertions/DeletionsButslowerIndexeDexedAccess,Lestpypytypypytypypytypy

pythonoffersFourmainMethodStoreMoveElement Fromalist:1)刪除(值)emovesthefirstoccurrenceofavalue,2)pop(index)emovesanderturnsanelementataSpecifiedIndex,3)delstatementremoveselemsbybybyselementbybyindexorslicebybyindexorslice,and 4)

toresolvea“ dermissionded”錯誤Whenrunningascript,跟隨台詞:1)CheckAndAdjustTheScript'Spermissions ofchmod xmyscript.shtomakeitexecutable.2)nesureThEseRethEserethescriptistriptocriptibationalocatiforecationAdirectorywherewhereyOuhaveWritePerMissionsyOuhaveWritePermissionsyYouHaveWritePermissions,susteSyAsyOURHomeRecretectory。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

WebStorm Mac版
好用的JavaScript開發工具

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

SublimeText3漢化版
中文版,非常好用

SublimeText3 Linux新版
SublimeText3 Linux最新版