python find the specific element position and return all distinct elements in front of it

Viewed 48

I have a python list:

a = [('x',3.6),('x',5.2),('y',4.5),('x',1.4),('y',2.1),('z',3.3)]

In a, I want to find top2 distinct element of a which sorted by the second element, which means:

First: I sorted a:

b = sorted(a, key=lambda x: x[1],reverse=True)

b: [('x', 5.2), ('x', 3.6), ('y', 3.5), ('z', 3.3), ('y', 2.1), ('x', 1.4)]

Second: in the sorted b, I need get two distinct element, which result may be: ['x', 'y'], how can I get this result neatly?

ADDED:

and if I have a list:

a = [('x',3.6, 'xx1'),('x',5.2, 'xx2'),('y',4.5, 'xx1'),('x',1.4, 'xx3'),('y',2.1, 'xx1'),('z',3.3, 'xx2')]

and b:

b = sorted(a, key=lambda x: x[1], reverse=True)

how can I get the top2 distinct elements(which result may be ['x', 'y']) of a?

1 Answers

Use OrderedDict and get the first 2 elements of its keys

from collections import OrderedDict
list(OrderedDict(sorted(a, key=lambda x: x[1], reverse=True)).keys())[:2]
Out[7]: ['x', 'y']

For more elements in each item of a, need to reformat the structure of elements of tuple when building the OrderedDict in a format of (key, (item1, item2, ...))

list(OrderedDict([(x[0], (x[1], x[2]) )for x in sorted(a, key=lambda x: x[1], reverse=True)]))[:2]
Out[10]: ['x', 'y']
Related