在Python中删除重复列表

2024-04-29 01:44:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个程序,输入一系列的数字,然后取其中的6个组合成不同的彩票号码。当我创建不同的组合时,我想删除重复项,这样每个组合只打印一次。 这就是我想要的:

combo_list = [1 2 3 4 5 6 7]

输出应为:

^{pr2}$

我正在使用代码:

   final = []
    for sublist in combo_list:
        if sublist not in final:
            final.append(sublist)
    for item in final:
        item = (sorted(item, key=int))
        print (' '.join(str(n) for n in item))

但是,当我使用代码时,会得到一个有许多重复项的输出:

1 2 3 4 5 6
1 2 3 4 5 7
1 2 3 4 5 6
1 2 3 4 6 7
1 2 3 4 5 7
1 2 3 4 6 7
1 2 3 4 5 6
1 2 3 4 5 7
1 2 3 4 5 6
1 2 3 5 6 7
1 2 3 4 5 7
1 2 3 5 6 7
1 2 3 4 5 6
1 2 3 4 6 7
1 2 3 4 5 6
1 2 3 5 6 7
1 2 3 4 6 7
1 2 3 5 6 7
1 2 3 4 5 7
1 2 3 4 6 7
1 2 3 4 5 7
1 2 3 5 6 7
1 2 3 4 6 7
1 2 3 5 6 7
1 2 3 4 5 6
.
.
.

有什么想法,我必须改变每个组合只打印一次?在


Tags: 代码in程序forifnot数字item
3条回答

如果我理解您的问题,请继续使用itertools模块中的combinations函数。在您的情况下,您将得到:

>>> import itertools
>>> list(itertools.combinations([1,2,3,4,5,6,7],6)
[(1, 2, 3, 4, 5, 6)
(1, 2, 3, 4, 5, 7)
(1, 2, 3, 4, 6, 7)
(1, 2, 3, 5, 6, 7)
(1, 2, 4, 5, 6, 7)
(1, 3, 4, 5, 6, 7)
(2, 3, 4, 5, 6, 7)] 

我想这就是你想要的。在

请记住,combinations函数的输出是一个生成器。在

使用^{}进行此操作:

import itertools as it
ans = it.combinations([1, 2, 3, 4, 5, 6, 7], 6)

结果应该是:

^{pr2}$

如果以后需要打印数字,很容易:

for r in ans:
    print ' '.join(str(s) for s in r) 

=> 1 2 3 4 5 6
   1 2 3 4 5 7
   1 2 3 4 6 7
   1 2 3 5 6 7
   1 2 4 5 6 7
   1 3 4 5 6 7
   2 3 4 5 6 7

您只需将源代码带到itertools.combinations然后:

def lotto(iterable, r):
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = range(r)
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

print list(lotto([1, 2, 3, 4, 5, 6, 7], 6))   

相关问题 更多 >