0

This is my list.

[('a', 12), ('c', 4), ('b', 3), ('e', 6), ('d', 5), ('g', 50), ('f', 30),]  

The result for sorting this list would be.

[('g', 50), ('f', 30), ('a', 12), ('e', 6), ('d', 5), ('c', 4), ('b', 3)]  

I tried using:

x = sorted(alpha_items, key=lambda x: x[1],)  

But I need to reverse it.

Can i add another key maybe?

Rtucan
  • 157
  • 1
  • 11

4 Answers4

6

The obvious way is to explicitly use the reverse parameter which exists precisely for that purpose:

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

If you're sorting by numbers, you can also just negate them:

sorted(alpha_items, key=lambda x: -x[1])
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
  • Or `reversed(alpha_items, key=lambda x: x[1])` – Malik Brahimi May 15 '15 at 21:46
  • @Malik, that doesn't work. [`reversed()` doesn't take any keyword arguments](https://docs.python.org/3.4/library/functions.html?highlight=reversed#reversed). – TigerhawkT3 May 15 '15 at 21:51
  • @TigerhawkT3 Oh, thanks. I never knew that. – Malik Brahimi May 15 '15 at 22:01
  • 1
    @MalikBrahimi I assume you mean `reversed(sorted...`? I had considered that but it gives you an iterator and more importantly I think it's just *wrong* to sort and then reverse instead of sorting in the desired order right away, especially since the reverse parameter exists for that. – Stefan Pochmann May 15 '15 at 22:02
  • @StefanPochmann No, I meant strictly reversed with a key, but I was wrong. – Malik Brahimi May 15 '15 at 22:38
2

operator.itemgetter(n) constructs a callable that assumes iterable object (list, tuple, set) as input an fetches n-th element out of it.

In [26]: mylist=[('a', 12), ('c', 4), ('b', 3), ('e', 6), ('d', 5), ('g', 50), ('f', 30),]

In [27]: from operator import itemgetter

In [30]: s_l=sorted(mylist,key=itemgetter(1),reverse=True)

In [31]: s_l
Out[31]: [('g', 50), ('f', 30), ('a', 12), ('e', 6), ('d', 5), ('c', 4), ('b', 3)]
Ajay
  • 5,267
  • 2
  • 23
  • 30
0

Why not a simple sorting algorithm like bubble?

Basically we check if:

a[i][1]<a[i+1][1]. 

If it is the case than we simply swap them.

Repeat.

Check sorting-algorithms.com and take look at the Bubble algorithm animation.

>>> a = [('a', 12), ('c', 4), ('b', 3), ('e', 6), ('d', 5), ('g', 50),('f', 30),]  
>>> for elem in range(len(a)-1, 0, -1): 
...   for i in range(elem):
...     if a[i][1]<a[i+1][1]:
...        a[i], a[i+1] = a[i+1], a[i]
... 
>>> a
[('g', 50), ('f', 30), ('a', 12), ('e', 6), ('d', 5), ('c', 4), ('b', 3)]
-1
alpha_items.sort(key=lambda s:s[1], reverse = True)
Iron Fist
  • 10,739
  • 2
  • 18
  • 34
  • Only the second one works. The first one sorts by _ascending_ value of the _last_ item, which just happens to be the second item. – TigerhawkT3 May 15 '15 at 21:35