如何从列表中两次删除包含相同数字的组合,重复地包含相同数字?

时间:2019-09-14 19:13:15

标签: python python-3.x python-2.7 list

我想键入从1到k的最多k个子序列的组合的代码。在这里,我试图找到即使列表包含两次也不包含相同数字的子序列。

我正在尝试这样做,但是第一部分却失败了。

import itertools

lst1=[1, 2, 3, 5, 6, 3, 9, 5, 1, 2]
k = int(input())
lst = [i for j in range(1,k+1) for i in itertools.combinations(lst1, j)]
set1 = set(lst)
print(lst)
print(set1)

代码应提供以下答案: [(1,2,3),(1,3,5)...等等),但它不应该给出(1,2,1)或(1,2,2),因为它包含重复的数字。 / p>

1 个答案:

答案 0 :(得分:0)

根据您的逻辑,我已编写此代码,以便从列表中删除重复的列表。

import itertools

lst1=[1, 2, 3, 5, 6, 3, 9, 5, 1, 2]
k = int(input())
lst = [i for j in range(1,k+1) for i in itertools.combinations(lst1, j)]
set1 = set(lst)
print(lst)
print(set1)
all_combination = list(set1)
new = []
status = False
for i in all_combination:
    for j in range(len(i)):
        l = j+1
        for k in range(l, len(i)):
            if i[j] == i[k] and i[j] not in new:
                status = True
                break
            else:
                status = False
        if status == True:
            break
    if status == False:
        new.append(i)
print(new)

但是您的示例答案显示了给定数量的长度为3或n的子集的组合。并从中删除重复项。这是我的代码,它将返回列表中长度为3或n的所有数字组合,并删除重复项,只需更改s的值,您将相应地得到组合。

l1 = [1, 2, 3, 5, 6, 3, 9, 5, 1, 2]
s = 3
new_list = []
all_combination = []
def combination(numbers, n, subset):
    if len(subset) == n:
        all_combination.append(subset)
    else:
        for i in range(len(numbers)):
            combination(numbers, n, subset + [numbers[i]])
combination(l1, s, new_list)
print(all_combination)
unique = []
status = False
for i in all_combination:
    for j in range(len(i)):
        l = j+1
        for k in range(l, len(i)):
            if i[j] == i[k] and i[j]:
                status = True
                break
            else:
                status = False
        if status == True:
            break

    if status == False:
        unique.append(i)
print(unique)

Output