首页 > 解决方案 > 使用生成器按多个属性对对象列表进行排序

问题描述

我有一个对象列表,这些对象的数量将在数千到数万之间。这些对象可以被认为是我希望根据他们的分数对其进行排名的人。

因此,首先他们按年龄分组,然后按性别等进行分组。在每个点上,都会提供与该年龄/性别类别相对应的排名。对象上的字段是age_groupgender。因此,您首先要收集具有该年龄组的每个人30-39,然后是该年龄组的所有男性 ( M) 和所有女性 ( W)。

在这些点中的每一个创建一个新列表都非常占用内存,因此我尝试使用生成器和来使用原始列表进行分组。所以我有一个功能可以做到这一点;

def group_standings(_standings, field):
    """ sort list of standings by a given field """
    getter = operator.attrgetter(field)
    for k, g in itertools.groupby(_standings, getter):
        yield list(g)


def calculate_positions(standings):
    """
    sort standings by age_group then gender & set position based on point value 
    """
    for age_group in group_standings(standings, 'age_group'):

        for gender_group in group_standings(age_group, 'gender'):

            set_positions(
                standings=gender_group,
                point_field='points',
                position_field='position',
            )

为了set_positions正常运行,它需要整个组,以便它可以按point_field值排序然后设置position_field值。

调试生成器groupby并没有像我预期的那样收集与键匹配的所有对象。输出类似于;

DEBUG generating k 30-39
DEBUG generating g [<Standing object at 0x7fc86fedbe10>, <Standing object at 0x7fc86fedbe50>, <Standing object at 0x7fc86fedbe90>]

DEBUG generating k 20-29
DEBUG generating g [<Standing object at 0x7fc86fedbed0>]

DEBUG generating k 30-39
DEBUG generating g [<Standing object at 0x7fc86fedbf10>]

DEBUG generating k 20-29
DEBUG generating g [<Standing object at 0x7fc86fedbf50>, <Standing object at 0x7fc86fedbf90>, <Standing object at 0x7fc86fedbfd0>, <Standing object at 0x7fc856ecc050>, <Standing object at 0x7fc856ecc090>, <Standing object at 0x7fc856ecc0d0>, <Standing object at 0x7fc856ecc110>, <Standing object at 0x7fc856ecc150>, <Standing object at 0x7fc856ecc190>, <Standing object at 0x7fc856ecc1d0>]

为了确认,为了set_positions发挥作用,生成器提供的列表需要包含20-29年龄组中的所有对象,但如上所述,来自该组的对象是在列表的多次迭代中找到的。

标签: pythongeneratoritertools

解决方案


发生这种情况是因为 groupby 函数假定输入的可迭代对象已经按键排序(请参阅文档)。它是为性能而设计的,但令人困惑。另外,我不会强制g转换为group_standings函数列表,而是仅在传递gender_groupset_positions.


推荐阅读