首页  >  文章  >  后端开发  >  这是适合您的文章的标题,请记住问题格式: 如何在 Python 中按类型对数据对进行分组:使用“defaultdict”和“itertools.groupby”的高效解决方案

这是适合您的文章的标题,请记住问题格式: 如何在 Python 中按类型对数据对进行分组:使用“defaultdict”和“itertools.groupby”的高效解决方案

Linda Hamilton
Linda Hamilton原创
2024-10-27 07:06:03765浏览

Here's a suitable title for your article, keeping the question format in mind: 

How to Group Data Pairs by Type in Python: Efficient Solutions with `defaultdict` and `itertools.groupby`

Python Group By

问题:

给定一组数据对,其中第一项是值,第二项是类型,根据类型进行分组。

示例:

input = [
  ('11013331', 'KAT'),
  ('9085267', 'NOT'),
  ('5238761', 'ETH'),
  ('5349618', 'ETH'),
  ('11788544', 'NOT'),
  ('962142', 'ETH'),
  ('7795297', 'ETH'),
  ('7341464', 'ETH'),
  ('9843236', 'KAT'),
  ('5594916', 'ETH'),
  ('1550003', 'ETH'),
]

期望结果:

result = [
  {
    'type': 'KAT',
    'items': ['11013331', '9843236']
  },
  {
    'type': 'NOT',
    'items': ['9085267', '11788544']
  },
  {
    'type': 'ETH',
    'items': ['5238761', '962142', '7795297', '7341464', '5594916', '1550003']
  },
]

解决方案:

第 1 步:创建字典

  • 使用 collections.defaultdict 创建一个字典,其中键是项目类型,值是存储值的列表。
  • 对于每个数据对,将值附加到与其类型对应的列表中。

第 2 步:转换为预期格式

  • 通过迭代其项目并使用“type”和“items”键创建字典,将字典转换为预期格式。

示例代码:

<code class="python">from collections import defaultdict

res = defaultdict(list)
for v, k in input:
    res[k].append(v)

output = [{'type': k, 'items': v} for k, v in res.items()]</code>

使用 itertools.groupby 的替代解决方案:

注意:此方法要求输入为已排序。

  • 根据数据对的类型对其进行排序。
  • 使用 itertools.groupby 按类型对数据对进行分组。
  • 迭代分组的项目以创建所需的输出格式。

示例代码:

<code class="python">from itertools import groupby, itemgetter

sorted_input = sorted(input, key=itemgetter(1))

groups = groupby(sorted_input, key=itemgetter(1))
output = [{'type': k, 'items': [x[0] for x in v]} for k, v in groups]</code>

按键顺序注意事项:

  • 在 3.7 之前的 Python 版本中,不保证字典的插入顺序。要保持顺序与输入一致,请使用 collections.OrderedDict。
  • 在 Python 3.7 及更高版本中,字典默认保留插入顺序。

以上是这是适合您的文章的标题,请记住问题格式: 如何在 Python 中按类型对数据对进行分组:使用“defaultdict”和“itertools.groupby”的高效解决方案的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn