Home > Blockchain >  Delete lists with same elements in this case words in a listbut in different order in Python
Delete lists with same elements in this case words in a listbut in different order in Python

Time:07-13

I have this list for example but there are more elements in the problem

data = [['USD','PEN'], ['GFY' ,'ARG'], ['TFG','RSD'], ['PEN','USD'], ['GFT','RSD']]

How can I eliminate the elements of the list that are repeated but in a different order, in this case the ['PEN','USD'] would be eliminated because the ['USD','PEN'] already exists in Python

CodePudding user response:

The idea is that we can check the existence by the sorted element. You can achieve this like below. You could make this more elegant.

data = [['USD','PEN'], ['GFY' ,'ARG'], ['TFG','RSD'], ['PEN','USD'], ['GFT','RSD']]

tmp = []
exists = set()
for x in data:
  x_sorted = tuple(sorted(x))
  if x_sorted not in exists:
    tmp.append(x)
    exists.add(x_sorted)
tmp
# [['USD', 'PEN'], ['GFY', 'ARG'], ['TFG', 'RSD'], ['GFT', 'RSD']]

CodePudding user response:

for entry in data:
    if "USD" in entry and "PEN" in entry:
        data.remove(entry)
  • Related