Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sort last
#3
You can use the itemgetter.

from operator import itemgetter

tup = [(1, 7), (1, 3), (3, 4, 5), (2, 2)]
sorted(tup, key=itemgetter(-1))
The itemgetter could also used to access keys in a dict:
data = [{"x": 10, "y": 42},{"x": 20, "y": 44},{"x": 13, "y": -1}]

# sort by x
sorted(d, key=itemgetter("x"))

# sort by x and then y
sorted(d, key=itemgetter("x", "y"))

# sort by y and then x
sorted(d, key=itemgetter("y", "x"))
How it works:

my_itemgetter = itemgetter(1)
# the itemgetter returns a callable, which takes the sequence as input
my_itemgetter([1,2,3])
Output:
2
If you call it in one line, it looks a bit strange:
itemgetter(1)([1,2,3])
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
Sort last - by pyzyx3qwerty - May-04-2020, 10:53 AM
RE: Sort last - by anbu23 - May-04-2020, 11:06 AM
RE: Sort last - by DeaD_EyE - May-04-2020, 11:33 AM
RE: Sort last - by pyzyx3qwerty - May-04-2020, 02:22 PM
RE: Sort last - by Yoriz - May-04-2020, 03:52 PM
RE: Sort last - by pyzyx3qwerty - May-05-2020, 10:48 AM
RE: Sort last - by pyzyx3qwerty - May-04-2020, 04:24 PM
RE: Sort last - by DeaD_EyE - May-05-2020, 02:58 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  how to sort a list without .sort() function letmecode 3 3,606 Dec-28-2020, 11:21 PM
Last Post: perfringo
  [split] Manual Sort without Sort function fulir16 2 3,332 Jun-02-2019, 06:13 AM
Last Post: perfringo
  Manual Sort without Sort function dtweaponx 26 49,911 Jun-01-2019, 06:02 PM
Last Post: SheeppOSU

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020