Eliminate redundant tuples

If I have a list of tuples, where each tuple represents variables a, band chow can I remove redundant tuples?

Redundant tuples are those where athey are bsimply interchangeable, but c- the same thing. So for this example:

tups = [(30, 40, 50), (40, 30, 50), (20, 48, 52), (48, 20, 52)]

my final list should only contain half the entries. One possible way out:

tups = [(30, 40, 50), (20, 48, 52)]

other

tups = [(40, 30, 50), (20, 48, 52)]

and etc.

Is there an easy Pythonic way to do this?

, (30, 40, 50) (40, 30, 50), , (, , " d ). 2 , .

, (, ), , , .

PS: PE # 39. PE, , ( ).

Edit

, PE # 39 - a, b c, , , a**2 + b**2 == c**2, a b .

+5
5
set([(a,b,c) if a<b else (b,a,c) for a,b,c in tups])
+7
tups = [(30, 40, 50), (40, 30, 50), (20, 48, 52), (48, 20, 52)] 
no_duplicates = list(set(tuple(sorted(tup)) for tup in tups))

, , , :

no_duplicates = list(set(tuple(sorted(tup[:2])) + (tup[2],) for tup in tups))

, tuple(sorted(tup[:2])) + (tup[2],) tuple(sorted(tup[:2])) + tup[2:], , tuple(sorted(tup[:i])) + tup[i:], i , .

+4

, - . , , - . , , :

>>> newTups = [(tuple(sorted([a, b])), c) for a, b, c in tups]
>>> newTups
[((30, 40), 50), ((30, 40), 50), ((20, 48), 52), ((20, 48), 52)]
>>> set(newTups)
set([((20, 48), 52), ((30, 40), 50)])
+4

frozenset set .

tups = [(30, 40, 50), (40, 30, 50), (20, 48, 52), (48, 20, 52)]

frozen_sets = { frozenset(x) for x in tups }

tups2 = [tuple(x) for x in frozen_sets]

, frozenset([1,2,3]) == frozenset([3,1,2]), , (1,2,3) != (3,1,2).

frozenset, set, :

TypeError: unhashable type: 'set'

frozenset .

+2

If you don't care about the order for the first two elements, you really don't want to use 3-uples: just convert to a new data structure that discards information that you don't need.

result = {({x[0],x[1]},x[2]) for x in tups}
+1
source

All Articles