【问题标题】:python group records together by fieldpython按字段将记录分组在一起
【发布时间】:2018-01-11 04:43:02
【问题描述】:

我有一组记录,我想在两个单独的字段中组合在一起。每条记录都是一个 python 字典。其中一个字段是日期值,另一个是数字字段。即:

h = [{'date': 20170728, 'group': 121, ...},
     {'date': 20170729, 'group': 131, ...},
     ...]

现在,如果我想将某些组分组在一起,例如在 [123, 134, 145] 中但日期相同的任何组,将它们分组在一起,但每个其他组都被自己分组在一起,我该怎么做做到这一点?

我正在使用以下代码:

grouped_list = []
for date, items in groupby(h, key=itemgetter('date'):
    g = list(items)
    grouped_list.append(g)

我正在寻找的输出如下:

grouped_list = [
                [records that have a distinct date value and group],
                [records that have a distinct date but are in the group [123, 134, 145],
               etc.]

组 123、134 和 145 中的记录在 grouped_list 中不应有各自的列表。它们应该在一个列表中组合在一起。

【问题讨论】:

  • 你能提供一个你正在寻找的输出的例子吗?
  • 使用grouped_records = sorted(h, key=lambda x: x['date']) 对列表进行排序是否适合您的需要?还是您在寻找其他东西?
  • 请注意collections.groupby 对连续迭代器进行分组。由于 dicts 的迭代顺序是不可预测的,这可能不是正确的方法

标签: python


【解决方案1】:

您可以编写一个自定义函数来计算对记录进行分组的键,如下所示:

from itertools import groupby

records = [
      {'date': 20170728, 'group': 121},
      {'date': 20170729, 'group': 131}, 
      {'date': 20170729, 'group': 134},
      {'date': 20170729, 'group': 145}, 
]
grouped_groups = [123, 134, 145]

def compute_groupby_key(entry): 
      return "%d-%d" % (
            entry['date'],
            grouped_groups[0] if entry['group'] in grouped_groups else entry['group']
      )

grouped_records = [list(entries) for key, entries in groupby(records, compute_groupby_key)]

这里grouped_records 包含:

[
    [{'date': 20170728, 'group': 121}],
    [{'date': 20170729, 'group': 131}],
    [{'date': 20170729, 'group': 134}, {'date': 20170729, 'group': 145}]]
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    相关资源
    最近更新 更多