Python 按键对数据进行分组
本指南解决了在 Python 中按特定键对数据进行分组的任务。我们的目标是为给定的数据集实现高效且有序的分组解决方案。
问题陈述
考虑以下表示为键值对的数据集:
<code class="python">input = [ ('11013331', 'KAT'), ('9085267', 'NOT'), ('5238761', 'ETH'), ('5349618', 'ETH'), ('11788544', 'NOT'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('9843236', 'KAT'), ('5594916', 'ETH'), ('1550003', 'ETH') ]</code>
目标是通过对应的键(每个元组中的第二个元素)对这些数据对进行分组,并以以下格式返回分组结果:
<code class="python">result = [ { 'type': 'KAT', 'items': ['11013331', '9843236'] }, { 'type': 'NOT', 'items': ['9085267', '11788544'] }, { 'type': 'ETH', 'items': ['5238761', '962142', '7795297', '7341464', '5594916', '1550003'] } ] </code>
解决方案
以下是有效对数据进行分组的步骤:
-
创建字典:使用 defaultdict 来存储每个键的项目。使用默认工厂初始化字典,为每个新键创建一个空列表。
<code class="python">from collections import defaultdict res = defaultdict(list) for v, k in input: res[k].append(v)</code>
-
将字典转换为预期格式:生成最终结果结果,将字典转换为具有所需结构的字典列表。
<code class="python">result = [{'type': k, 'items': v} for k, v in res.items()]</code>
可选注释:
- 之前Python 3.7,字典不维护插入顺序。要保留键的原始顺序,请考虑使用 OrderedDict。
- 或者,也可以使用 itertools.groupby 函数进行分组,但它需要预先对输入进行排序。
- 对于大型数据集,使用具有分组功能的数据库可能比此处介绍的内存解决方案更有效。
以上是如何在Python中按键对数据进行分组并以特定格式返回结果,有效处理具有重复键的数据并保持顺序?的详细内容。更多信息请关注PHP中文网其他相关文章!

Python是解释型语言,但也包含编译过程。1)Python代码先编译成字节码。2)字节码由Python虚拟机解释执行。3)这种混合机制使Python既灵活又高效,但执行速度不如完全编译型语言。

useeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.ForloopSareIdeAlforkNownsences,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐个偏置,零indexingissues,andnestedloopineflinefficiencies

forloopsareadvantageousforknowniterations and sequests,供应模拟性和可读性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

WebStorm Mac版
好用的JavaScript开发工具

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Atom编辑器mac版下载
最流行的的开源编辑器