Python问题删除列表中的重复项
问题描述:
我遇到了从我的输出中删除所有重复项的问题。目前使用Tkinter接受用户输入...在4个不同的文本框中包含4个单词。目标是打印所有单词的排列。Python问题删除列表中的重复项
def exactMatch(entries):
for entry in entries:
words = [entry[1].get() for entry in entries]
perms = [p for p in permutations((words))]
l1 = []
for words in perms:
#perms2 = ','.join(str(v) for v in perms)
l1.append(perms)
l2 = ','.join([str(l1) for word in l1])
l3 = l2.replace("," , ' ') #Takes out the Quotations
l4 = l3.replace("'" , ' ') # Takes out the commas
sorted_list = sorted(set(l4))
#unique_list = list(OrderedDict(zip(l4, repeat(None))))
#for i in l4:
# if i not in l5:
# l5.append(i)
print(sorted_list)
输出......当试图从4个字,我们键入得到排列低于(PS仅仅只是输出/没有重复片段)的问题是,它是打印很多重复和产生大量输出。
(hi w2 w4 w3) (hi w3 w2 w4) (hi w3 w4 w2) (hi w4 w2 w3) (hi w4 w3 w2) (w2 hi w3 w4) (w2 hi w4 w3) (w2 w3 hi w4) (w2 w3 w4 hi)
香港专业教育学院试图执行使用集以及删除重复的一种手段,但产量不想要的结果。当键入 “W1,W2,W3,W4” 的输出就......
sorted_list = sorted(set(l4)) <- set code
[' ', '(', ')', '1', '2', '3', '4', '[', ']', 'w']
[' ', '(', ')', '1', '2', '3', '4', '[', ']', 'w']
[' ', '(', ')', '1', '2', '3', '4', '[', ']', 'w']
[' ', '(', ')', '1', '2', '3', '4', '[', ']', 'w']
谁能帮帮忙?
答
看起来像是使事情变得比所需要的复杂得多,并在过程中造成错误。你的代码结构非常混乱,你似乎多次做同样的事情。
如果输入真的是in = "w1,w2,w3,w4"
像你说的,我们可以对,
只是
- 斯普利特:
words = in.split(',')
,这会导致列表['w1', 'w2', 'w3', 'w4']
。 - 将单词转换为
set
以删除重复项:words = set(words)
。 - 获取排列
perms = itertools.permutations(words)
。 - 打印排列
print(list(perms))
。
如果你得到一个单词列表从Tkinter的在entries
回来,因为你的代码似乎在暗示,你甚至都不需要一步有关的顺序1.
注意排列护理元素。有4! = 24个排序四个独特元素的方法,所以你应该在你的输出中预期24个排列。如果这超出了你的预期,也许你正在考虑错误的组合函数。