


Python でペアのリストを各ペアの 2 番目の要素で効率的にグループ化し、グループ化された結果内の最初の要素をリストとして保持するにはどうすればよいでしょうか?
Python Group By
最初の要素をリストとして保持しながら、各ペアの 2 番目の要素でデータ ペアのセットをグループ化する必要がある場合があります。グループ化された結果。これは、次の手順を使用して Python で効率的に実現できます。
辞書の使用
コレクション モジュールのdefaultdictを使用して辞書を作成します。キーはペアの 2 番目の要素です。次に、入力リストを反復処理し、最初の要素を対応するキーの値に追加します。
<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 を使用しますが、入力リストを 2 番目の要素でソートする必要があります。
<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>
内包表記を使用して辞書のリストを作成します。
<code class="python">result = [{'type': k, 'items': [x[0] for x in v]} for k, v in groups]</code>
Python バージョンに関する考慮事項
Python 3.7 より前では、辞書内のキーの順序は保持されません。元の順序を維持するには、collections.OrderedDict を使用します。
<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 以降、通常の辞書は挿入順序を維持するため、OrderedDict は必要なくなりました。
以上がPython でペアのリストを各ペアの 2 番目の要素で効率的にグループ化し、グループ化された結果内の最初の要素をリストとして保持するにはどうすればよいでしょうか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

pythonusesahybridmodelofcompilation andtertation:1)thepythoninterpretercompilessourcodeodeplatform-indopent bytecode.2)thepythonvirtualmachine(pvm)thenexecuteTesthisbytecode、balancingeaseoputhswithporformance。

pythonisbothintersedand compiled.1)it'scompiledtobytecode forportabalityacrossplatforms.2)bytecodeisthenは解釈され、開発を許可します。

loopsareideal whenyouwhenyouknumberofiterationsinadvance、foreleloopsarebetterforsituationsは、loopsaremoreedilaConditionismetを使用します

henthenumber ofiterationsisknown advanceの場合、dopendonacondition.1)forloopsareideal foriterating over for -for -for -saredaverseversives likelistorarrays.2)whileopsaresupasiable forsaresutable forscenarioswheretheloopcontinupcontinuspificcond

pythonisnotpurelyLepted; itusesahybridapproachofbytecodecodecodecodecodecodedruntimerttation.1)pythoncompilessourcodeintobytecode、whodythepythonvirtualmachine(pvm).2)

はい、youcanconcatenateListsusingingaloopinpython.1)useSeparateloopsforeachlisttoeditemstoaresultlist.2)useanestededLooptoAverMultiplElistsForomerConciseapproach.3)applylogingduringConcateNation for forteringEnlumbers

CONCATENATINGLISSTINPYTHONARE:1)theExtend()MethodForin-PlaceModification、2)itertools.chain()formeMoryeficiency withlaredatasets.theextend()MethodModifiestheoriginallist、MakingMemory-efficitientButReisifRecurityifpRESPRESRINVINING

Pythonloopsは、forloopsealforsecences andwhilelcondition basedrepetition.bestPracticesInvolveを使用して、Pythonloopsincludeを使用します


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

SAP NetWeaver Server Adapter for Eclipse
Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

メモ帳++7.3.1
使いやすく無料のコードエディター

EditPlus 中国語クラック版
サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

ZendStudio 13.5.1 Mac
強力な PHP 統合開発環境
