gpt4 book ai didi

python - 从结果集中消除连续的数字组合

转载 作者:太空宇宙 更新时间:2023-11-04 01:31:04 24 4
gpt4 key购买 nike

我有一个包含 30 个数字的列表:

[1, 3, 5, 6, 7, 8, 9, 10, 15, 19, 20, 22, 23, 24, 26, 27, 28, 32, 33, 35, 37, 38, 39, 40, 41, 42, 43, 44, 47, 48]

我正在打印所有可能的 8 位数字组合,使用此代码效果很好:

possible_combinations = itertools.combinations(dedup_list, 8) 

combos = []
for e in possible_combinations:
combos.append(e)
print combos

我现在想做的是消除所有包含连续 3 位数字的组合,例如:

[1, 5, 9,22, 23, 24, 33, 37]

建议?

最佳答案

我认为这可以解决问题:

from itertools import combinations, groupby
from operator import itemgetter

data = [1, 3, 5, 6, 7, 8, 9, 10, 15, 19, 20, 22, 23, 24, 26, 27, 28, 32, 33, 35, 37, 38, 39, 40, 41, 42, 43, 44, 47, 48]

def find_consecutive(lst, min_string=3):
for k, g in groupby(enumerate(lst), lambda (i,x):i-x):
num_string = map(itemgetter(1), g)
if len(num_string) >= 3:
yield num_string

for i in combinations(data, 8):
if not any(find_consecutive(i, min_string=3)):
print i

返回:

(1, 3, 5, 6, 8, 9, 15, 19)
(1, 3, 5, 6, 8, 9, 15, 20)
(1, 3, 5, 6, 8, 9, 15, 22)
(1, 3, 5, 6, 8, 9, 15, 23)
(1, 3, 5, 6, 8, 9, 15, 24)

...等等,等等

关于python - 从结果集中消除连续的数字组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13889186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com