从列表中删除排列

时间:2018-08-18 15:20:49

标签: python-3.x combinations

我正在尝试从排列列表中删除重复项,只保留组合,编号列表如下:

[[1, 3, 11, 13], [1, 7, 11, 9], [1, 9, 11, 7], [1, 15, 9, 3], [3, 1, 11, 13], [3, 5, 11, 9], [3, 15, 9, 1], [5, 3, 11, 9], [5, 11, 9, 3], [5, 13, 9, 1], [7, 1, 11, 9], [7, 11, 9, 1], [9, 1, 11, 7], [11, 5, 9, 3], [11, 7, 9, 1], [13, 5, 9, 1], [15, 1, 9, 3], [15, 3, 9, 1]]

这是我做过的一种方法,但是打印的列表中没有一个是空的:

def permtocomb(fcombs):
     fcombinations=fcombs 
     global value
     global comp
     global count
     global combs
     global b
     for z in range(0,len(fcombinations)):
         count = 0
         print('testing array'+str(fcombinations[z]))
         for x in range(0,4):
             value=fcombinations[z][x]
             for j in range(0,len(fcombinations)):

                 print('against arrqay'+str(fcombinations[j]))
                 for v in range(0,4):
                     if value==fcombinations[j][v]:
                         count+=1
                         b=j
         if count<=3:
             #fcombinations.pop(fcombinations[c])
             combs.append(fcombinations[b])


    permtocomb(fcombinations)
    print(fcombinations)
    print(combs)

是否有一些python插件或内置插件能够在不离开组合的情况下删除排列?

1 个答案:

答案 0 :(得分:2)

使用全局变量通常是一个坏主意,因为这会使调试变得非常困难。
这是一种非常简单的方法,只需记录一下您拥有的seen。您可以使用set来忽略组合,但是set是不可散列的,因此您可以使用frozenset,例如:

In []:
data = [[1, 3, 11, 13], ...]
seen = set()
result = []
for d in data:
    if frozenset(d) not in seen:
        result.append(d)
        seen.add(frozenset(d))
result

Out[]:
[[1, 3, 11, 13], [1, 7, 11, 9], [1, 15, 9, 3], [3, 5, 11, 9], [5, 13, 9, 1]]

如果您不关心订单,可以简化以下操作:

In []:
[list(e) for e in set(frozenset(d) for d in data)]

Out[]:
[[1, 11, 9, 7], [11, 1, 3, 13], [9, 13, 5, 1], [1, 3, 9, 15], [11, 9, 3, 5]]

但是,如果您真的不关心订单,可以将其保留为set的{​​{1}}:

frozenset

注意:这假定每个元素中都没有重复的值(示例数据中没有),如果您有多个值,则需要切换到多集(set(frozenset(d) for d in data) )。 / p>

相关问题