Python:以随机顺序删除一对重复的字符串 [英] Python: Remove pair of duplicated strings in random order

查看:92
本文介绍了Python:以随机顺序删除一对重复的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下列表

[('generators', 'generator'), ('game', 'games'), ('generator', 'generators'), ('games', 'game'), ('challenge', 'challenges'), ('challenges', 'challenge')]

('game', 'games')('games', 'game')有点相同,但是顺序不同.

Pairs ('game', 'games') and ('games', 'game') are kind of same but they are in different order.

我想要实现的输出

[('generators', 'generator'), ('games', 'game'), ('challenge', 'challenges')]

如何从上面的列表中删除配对?

How can I remove pairs as such from above list ?

任何建议,深表感谢.

推荐答案

您可以在集合中使用无序的可哈希数据结构. frozenset()是您的朋友在这里:

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.

这篇关于Python:以随机顺序删除一对重复的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆