开发者

Need an easy way to remove duplicates of nested tuples in python

I am currently working with a script that has lists that looks like this:

example = [ ((2,1),(0,1)), ((0,1),(2,1)), ((2,1),(0,1)) ]

Now turning this list to a set returns:

set( [ ((2,1),(0,1)), 开发者_高级运维((0,1),(2,1)) ] )

For my purposes I need to recognize these tuples as being equal as well. I dont care about retaining the order. All solutions I can think of is really messy so if anyone has any idea I would be gratefull.


It sounds like you may be off using frozensets instead of tuples.

>>> x = [((2, 1), (0, 1)), ((0, 1), (2, 1)), ((2, 1), (0, 1))]
>>> x
[((2, 1), (0, 1)), ((0, 1), (2, 1)), ((2, 1), (0, 1))]
>>> set(frozenset(ts) for ts in x)
set([frozenset([(0, 1), (2, 1)])])


In [10]: set(tuple(sorted(elt)) for elt in example)
Out[10]: set([ ((0, 1), (2, 1)) ])


First transform all elements to sets too. Then make a set of the whole list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜