Python: Remove pair of duplicated strings in random order

情到浓时终转凉″ 提交于 2019-12-20 02:59:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!