首页 > 解决方案 > 按模数对列表项进行分组?

问题描述

我创建了一个包含 14 个整数的列表。我想按模数对它们进行分组。我可以将它们分组,但我不想在同一组中重复数字。

例如:

[13, 40, 42, 17, 43, 45, 45, 6, 7, 7, 46, 48, 22, 51]

输出:

[[13], [40], [42], [17, 43], [45, 45, 6], [7, 7, 46], [48, 22], [51]]

但应该是:

[[13], [40], [42], [17, 43],[45],[45, 6],[7],[ 7, 46], [48, 22], [51]]

我的代码

def projection(val):
    return val %13 

player1_sorted = sorted(player1,key=projection)
print(player1_sorted)
player1_grouped = [list(it) for k, it in groupby(player1_sorted, projection)] 

标签: python

解决方案


您可以编写一个函数来拆分子列表:

from itertools import groupby, chain

def chunker(it):
    chunk = []
    for x in it:
        if chunk and x == chunk[-1]:
            yield chunk
            chunk = []
        chunk.append(x)
    if chunk:
        yield chunk


[*chain(*([*chunker(g)] for _, g in groupby(player1, key=projection)))]
# [[13], [40], [42], [17, 43], [45], [45, 6], [7], [7, 46], [48, 22], [51]]

推荐阅读