问题描述
使用此代码:
from itertools import product
list1 = ['Gabe', 'Taylor', 'Kyle', 'Jay']
list2 = ['Gabe', 'Taylor', 'Kyle', 'Jay', 'James', 'John', 'Tyde','Chris', 'Bruno', 'David']
list3 = ['Gabe', 'Taylor', 'Kyle', 'Jay', 'James', 'John', 'Tyde','Chris', 'Bruno', 'David']
list4 = ['Kyle', 'James', 'John', 'Tyde','Bruno', 'Drew', 'Chris']
list5 = ['James', 'John', 'Brendan','Tim', 'Drew' ]
FinalList = []
for x in product(list1, list2, list3, list4, list5):
# check for duplicates
if len(set(x)) == 5:
FinalList.append(x)
# to print
for x in FinalList:
print x
我打印出所有唯一列表.但是,许多打印列表是唯一的,只是因为它们是相同元素,但顺序不同.
I print out all unique lists. However many of the printed lists are unique only because they are the same elements in a different order.
如何更改代码,以便仅在列表打印顺序不同的情况下才打印列表?
How can I change my code so that I only print a list if it hasn't already been printed just ordered differently?
推荐答案
与其检查集合的大小,不如将它们的每个都存储在集合中(这使查找变得简单).
Instead of checking the size of the set, as you do, store each of them, also in a set (it makes lookup simple).
然后检查您是否已经知道set(x)
;如果可以,请跳过它,否则将其放入一组已知的集合中.
Then check is you already know the set(x)
; if you do, skip it, else put it into the set of known sets.
要将集合存储在集合中,必须使用frozenset
而不是set
使内部集合不可变.
To store a set in a set, you have to make the inner set immutable, by using frozenset
instead of set
.
工作代码:
from itertools import product
list1 = ['Gabe', 'Taylor', 'Kyle', 'Jay']
list2 = ['Gabe', 'Taylor', 'Kyle', 'Jay', 'James', 'John', 'Tyde','Chris', 'Bruno', 'David']
list3 = ['Gabe', 'Taylor', 'Kyle', 'Jay', 'James', 'John', 'Tyde','Chris', 'Bruno', 'David']
list4 = ['Kyle', 'James', 'John', 'Tyde','Bruno', 'Drew', 'Chris']
list5 = ['James', 'John', 'Brendan','Tim', 'Drew' ]
def FindUniques(*lists):
already_seen = set()
result = []
for x in product(*lists):
icicle = frozenset(x)
if icicle not in already_seen:
result.append(x)
already_seen.add(icicle)
return result
final_list = FindUniques(list1, list2, list3, list4, list5)
# make sure that each element in final_list, independent of elemet order, is unique
assert len(final_list) == len(set(tuple(sorted(list(x))) for x in final_list))
# to print
for x in final_list:
print x
这篇关于仅保留唯一区别在于顺序的List的唯一实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!