Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform a pair of values into a sorted unique array?

Tags:

python

I have a result like this:

[(196, 128), (196, 128), (196, 128), (128, 196),
 (196, 128), (128, 196), (128, 196), (196, 128),
 (128, 196), (128, 196)]

And I'd like to convert it to unique values like this, in sorted order:

[128, 196]

And I'm pretty sure there's something like a one-liner trick in Python (batteries included) but I can't find one.

like image 713
Olivier Pons Avatar asked Feb 27 '16 09:02

Olivier Pons


1 Answers

Create the set union of all tuples, then sort the result:

sorted(set().union(*input_list))

Demo:

>>> input_list = [(196, 128), (196, 128), (196, 128), (128, 196),
...  (196, 128), (128, 196), (128, 196), (196, 128),
...  (128, 196), (128, 196)]
>>> sorted(set().union(*input_list))
[128, 196]
like image 123
Martijn Pieters Avatar answered Nov 04 '22 00:11

Martijn Pieters