Removing elements of a python list containing 2 identical elements

I have a list myList that contains form elements

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

      

The first and second elements are equal, as well as the third and fourth, although their first and second elements are swapped. I would like to keep just one of them so that the final list looks like this:

a, b, 3

s, d, 1

d, f, 4

+3


source to share


4 answers


If you want to preserve the order of the tuples and always keep the 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] ]

      

+1


source


Using kits and freezones to remove equal elements:

>>> 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 be sorted, but you want.

+4


source


Take each tuple in myList, convert it to a list, and sorted (). This will result in a list filled with sorted inner lists that will 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)))

      

+2


source


You can use this to maintain order tuples

internally list

and eliminate duplicates withset

>>> 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)]

      

+1


source







All Articles