0

I have a list contaning tuples

a = [('TV-MA', 1348), ('TV-14', 1038), ('R', 506), ('TV-PG', 432), ('PG-13', 286), ('NR', 202), ('PG', 183), ('TV-G', 80), ('TV-Y7', 69), ('TV-Y', 41)]

I want to sort a based on value in another list

b = ['TV-MA', 'TV-14', 'TV-PG', 'R', 'PG-13', 'NR', 'PG', 'TV-Y7', 'TV-G', 'TV-Y']

How to do this?

  • 1
    Does this answer your question? [Sorting list based on values from another list?](https://stackoverflow.com/questions/6618515/sorting-list-based-on-values-from-another-list) – damores Jul 29 '20 at 12:23

2 Answers2

3

You can use sorted with the key that returns the index of element from the second list

>>> sorted(a, key=lambda x: b.index(x[0]))
[('TV-MA', 1348), ('TV-14', 1038), ('TV-PG', 432), ('R', 506), ('PG-13', 286), ('NR', 202), ('PG', 183), ('TV-Y7', 69), ('TV-G', 80), ('TV-Y', 41)]

To speedup the index lookup, you can create a tmp dict that contains the index of the various elements in the second list

>>> d = dict(zip(b, range(len(b))))
>>> sorted(a, key=lambda x: d[x[0]])
[('TV-MA', 1348), ('TV-14', 1038), ('TV-PG', 432), ('R', 506), ('PG-13', 286), ('NR', 202), ('PG', 183), ('TV-Y7', 69), ('TV-G', 80), ('TV-Y', 41)]
Prem Anand
  • 2,469
  • 16
  • 16
2

use this -

b = sorted(a, key=lambda x:x[1], reverse=True)
b
[('TV-MA', 1348),
 ('TV-14', 1038),
 ('R', 506),
 ('TV-PG', 432),
 ('PG-13', 286),
 ('NR', 202),
 ('PG', 183),
 ('TV-G', 80),
 ('TV-Y7', 69),
 ('TV-Y', 41)]

If you only want the first element then -

b = [i[0] for i in b]
b
['TV-MA', 'TV-14', 'R', 'TV-PG', 'PG-13', 'NR', 'PG', 'TV-G', 'TV-Y7', 'TV-Y']

In one line -

b = [i[0] for i in sorted(a, key=lambda x:x[1], reverse=True)]
b
['TV-MA', 'TV-14', 'R', 'TV-PG', 'PG-13', 'NR', 'PG', 'TV-G', 'TV-Y7', 'TV-Y']
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51