python - 按模数对列表项进行分组?
问题描述
我创建了一个包含 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)]
解决方案
您可以编写一个函数来拆分子列表:
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]]
推荐阅读
- asp.net - 由于 Castle.Core 卡在实体框架中
- javascript - 定位标签的值
- python - 更改用于在运行时访问连接到 django 网站的数据库的用户
- javascript - gremlin-javascript 中的纯文本 SASL 身份验证
- python - 如何在 Kivy 中获取光标的位置?
- ios - 徽章数量始终为一个(云功能)
- javascript - 替换字符串索引处的字符
- python-3.x - sklearn.datasets.make_classification 无法生成平衡类
- docker - 从主机连接到 docker 进程
- java - 如何在 Map.of 工厂中保留插入顺序?