Python按模分组列表元素时如何避免同一分组内出现重复数值
解决方案
你当前的逻辑仅按模13的结果排序、分组,所有模13结果相同的元素都会被分到同一组,因此会出现相同数值在同一组的情况。可以参考以下两种修改方案:
方案1:手动遍历分组(逻辑清晰易维护)
先按模13排序,再遍历排序后的列表,同时判断模是否匹配、数值是否重复,按需拆分组:
from itertools import groupby def projection(val): return val % 13 player1 = [13, 40, 42, 17, 43, 45, 45, 6, 7, 7, 46, 48, 22, 51] # 先按模13结果排序 player1_sorted = sorted(player1, key=projection) player1_grouped = [] current_mod = None for num in player1_sorted: mod = projection(num) # 无分组/模不匹配/当前值和组内最后一个值重复,就开新组 if not player1_grouped or mod != current_mod or num == player1_grouped[-1][-1]: player1_grouped.append([num]) current_mod = mod else: player1_grouped[-1].append(num) print(player1_grouped)
运行输出和你要求的预期结果完全一致:[[13], [40], [42], [17, 43], [45], [45, 6], [7], [7, 46], [48, 22], [51]]
方案2:自定义groupby分组键(代码更简洁)
给groupby传入带状态的键生成函数,让连续相同的数值生成不同的分组键,自动完成拆分:
from itertools import groupby def projection(val): return val % 13 def gen_group_key(): last_num = None cnt = 0 def inner(num): nonlocal last_num, cnt if num == last_num: cnt += 1 last_num = num return (projection(num), cnt) return inner player1 = [13, 40, 42, 17, 43, 45, 45, 6, 7, 7, 46, 48, 22, 51] player1_sorted = sorted(player1, key=projection) group_key = gen_group_key() player1_grouped = [list(it) for k, it in groupby(player1_sorted, group_key)] print(player1_grouped)
这里用闭包封装了状态变量,避免使用全局变量,运行结果和方案1完全一致。
内容的提问来源于stack exchange,提问作者Rel0ad
相关产品推荐
相关产品推荐

