Python: Remove pair of duplicated strings in rando

2019-02-26 10:18发布

问题:

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