简体   繁体   English

删除包含2个相同元素的Python列表项

[英]Removing Python List Items that Contain 2 of the Same Elements

I have a list myList, which contains items of the form 我有一个列表myList,其中包含表单的项目

myList = [('a','b',3), ('b','a',3), ('c','d',1), ('d','c',1), ('e','f',4)]

The first and second items are equal and so are the third and fourth, although their first and second elements are swapped. 第一和第二项是相同的,第三和第四项也是相同的,尽管它们的第一和第二元素是交换的。 I would like to keep only one of each so that the final list looks like this: 我想只保留其中一个,以便最终列表如下所示:

a,b,3 A,B,3

c,d,1 C,d,1

e,f,4 E,F,4

Use sets and frozensets to remove equal elements: 使用sets和frozensets删除相同的元素:

>>> mySet = [frozenset(x) for x in myList]
>>> [tuple(x) for x in set(mySet)]
[('a', 3, 'b'), (4, 'e', 'f'), (1, 'c', 'd')]

the result can then be sorted however you'd like. 然后可以按照您的喜好对结果进行排序。

Take each tuple in myList, convert it to a list and apply sorted(). 获取myList中的每个元组,将其转换为列表并应用sorted()。 This results in a list filled with sorted inner lists which would look like. 这导致列表中填充了排序的内部列表,看起来像。

myList = [('a','b',3), ('b','a',3), ('c','d',1), ('d','c',1), ('e','f',4)]
sorted_inner_list = [sorted(list(element)) for element in myList]
output = list(set(map(tuple,sorted_inner_list)))

You can use this to maintain the order of your tuples inside list and eliminate the duplicates by using set 您可以使用它来维护list中的tuples顺序,并使用set消除重复项

>>> myList = [('a','b',3), ('b','a',3), ('c','d',1), ('d','c',1), ('e','f',4)]
>>> _ = lambda item: ([str,int].index(type(item)), item)
>>> sorted(set([tuple(sorted(i, key = _)) for i in myList]), key=lambda x: x[0])

Output: 输出:

[('a', 'b', 3), ('c', 'd', 1), ('e', 'f', 4)]

If yo want to keep order of tuple, and always keep first tuple when there are duplicates , you can do : 如果你想保持元组的顺序,并且在有重复时总是保持第一元组,你可以这样做:

>>> sets = [ frozenset(x) for x in myList ]
>>> filtered = [ myList[i] for i in range(len(myList)) if set(myList[i]) not in sets[:i] ]
>>> filtered
[('a', 'b', 3), ('c', 'd', 1), ('e', 'f', 4)]

If you prefer not to use another variable : 如果您不想使用其他变量:

filtered = [ myList[i] for i in range(len(myList))
            if set(myList[i]) not in [ frozenset(x) for x in myList ][:i] ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM