Python:生成“元组集";来自“元组列表";不考虑顺序
问题描述
如果我有如下的元组列表:
If I have the list of tuples as the following:
[('a', 'b'), ('c', 'd'), ('a', 'b'), ('b', 'a')]
我想删除重复的元组(在内容和内部项目的顺序方面重复),以便输出为:
I would like to remove duplicate tuples (duplicate in terms of both content and order of items inside) so that the output would be:
[('a', 'b'), ('c', 'd')]
或者
[('b', 'a'), ('c', 'd')]
我尝试将其转换为设置然后列表,但输出将同时保持 ('b', 'a')
和 ('a', 'b')
在结果集中!
I tried converting it to set then to list but the output would maintain both ('b', 'a')
and ('a', 'b')
in the resulting set!
解决方案
试试这个:
a = [('a', 'b'), ('c', 'd'), ('a', 'b'), ('b', 'a')]
b = list(set([ tuple(sorted(t)) for t in a ]))
[('a', 'b'), ('c', 'd')]
让我们分解一下:
如果你对一个元组进行排序,它就会变成一个排序列表.
If you sort a tuple, it becomes a sorted list.
>>> t = ('b', 'a')
>>> sorted(t)
['a', 'b']
对于 a
中的每个元组 t
,对其进行排序并将其转换回元组.
For each tuple t
in a
, sort it and convert it back to a tuple.
>>> b = [ tuple(sorted(t)) for t in a ]
>>> b
[('a', 'b'), ('c', 'd'), ('a', 'b'), ('a', 'b')]
将结果列表 b
转换为集合:值现在是唯一的.将其转换回列表.
Convert the resulting list b
to a set : values are now unique. Convert it back to a list.
>>> list(set(b))
[('a', 'b'), ('c', 'd')]
等等!
请注意,您可以使用 b="noreferrer">生成器 而不是 列表理解.
Note that you can skip the creation of the intermediate list b
by using a generator instead of a list comprehension.
>>> list(set(tuple(sorted(t)) for t in a))
[('a', 'b'), ('c', 'd')]
相关文章