问题
I have a list as below
[('generators', 'generator'), ('game', 'games'), ('generator', 'generators'), ('games', 'game'), ('challenge', 'challenges'), ('challenges', 'challenge')]
Pairs ('game', 'games')
and ('games', 'game')
are kind of same but they are in different order.
The output I am trying to achieve
[('generators', 'generator'), ('games', 'game'), ('challenge', 'challenges')]
How can I remove pairs as such from above list ?
Any suggestions, greatly appreciated.
回答1:
You can use an unordered hashable data structure within a set. frozenset()
is your friend here:
In [7]: {frozenset(i) for i in your_list}
Out[7]:
{frozenset({'generator', 'generators'}),
frozenset({'game', 'games'}),
frozenset({'challenge', 'challenges'})}
Note that in order to avoid looping over your list it's better to do this at the first place while creating your list.
回答2:
You could sort the list and then take every other index using list comprehension
lista = [i for i in sorted(tups)[::2]]
# [('challenge', 'challenges'), ('game', 'games'), ('generator', 'generators')]
来源:https://stackoverflow.com/questions/52686600/python-remove-pair-of-duplicated-strings-in-random-order