Python Forum
sorting a list of lists by an element
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
sorting a list of lists by an element
#2
Use sorted with a custom key function
data = [[0, False, "c"], [0, True, "z"], [1, False, "P"], [0, True, "A"]]
sorted_data = sorted(data, key=lambda x: x[1], reverse=True)
print(sorted_data)
Output:
[[0, True, 'z'], [0, True, 'A'], [0, False, 'c'], [1, False, 'P']]

Instead of using lamda you can also use itemgetter from the operator module
from operator import itemgetter

data = [[0, False, "c"], [0, True, "z"], [1, False, "P"], [0, True, "A"]]
sorted_data = sorted(data, key=itemgetter(1), reverse=True)
print(sorted_data)
Reply


Messages In This Thread
sorting a list of lists by an element - by leapcfm - Sep-10-2021, 03:13 PM
RE: sorting a list of lists by an element - by Yoriz - Sep-10-2021, 03:20 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  element in list detection problem jacksfrustration 5 427 Apr-11-2024, 05:44 PM
Last Post: deanhystad
  list in dicitonary element problem jacksfrustration 3 745 Oct-14-2023, 03:37 PM
Last Post: deanhystad
  Need help with sorting lists as a beginner Realist1c 1 768 Apr-25-2023, 04:32 AM
Last Post: deanhystad
  List all possibilities of a nested-list by flattened lists sparkt 1 936 Feb-23-2023, 02:21 PM
Last Post: sparkt
  user input values into list of lists tauros73 3 1,085 Dec-29-2022, 05:54 PM
Last Post: deanhystad
  Find (each) element from a list in a file tester_V 3 1,247 Nov-15-2022, 08:40 PM
Last Post: tester_V
  returning a List of Lists nafshar 3 1,102 Oct-28-2022, 06:28 PM
Last Post: deanhystad
  Сheck if an element from a list is in another list that contains a namedtuple elnk 8 1,868 Oct-26-2022, 04:03 PM
Last Post: deanhystad
  Creating list of lists, with objects from lists sgrinderud 7 1,700 Oct-01-2022, 07:15 PM
Last Post: Skaperen
  List Sorting Problem ZZTurn 5 1,364 Sep-22-2022, 11:23 PM
Last Post: ZZTurn

Forum Jump:

User Panel Messages

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