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
source to share
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] ]
source to share
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)))
source to share
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)]
source to share