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
#1
Hi,

I have a list of lists that I want to sort, something like :

data = [[0,False,'c'], [0,True,'z'], [1,False,'P'], [0,True,'A']]
I want all lists that have a True value at the top of Data, like :

sortingFuntion(data) = [[0,True,'z'], [0,True,'A'], [0,False,'c'], [1,False,'P']]
I can access the boolean with Data[i][1] in a for loop but I can't come up with how to transmit that value as a criteria to sorted()

Thanks
Yoriz write Sep-10-2021, 03:16 PM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#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
#3
And for the folks that don't like lambdas, in this case itemgetter is possible as well.

from operator import itemgetter
[...]
sorted_data = sorted(data, key=itemgetter(1), reverse=True)
Reply
#4
Thanks a lot !

I am fairly new to programming, will look up the lamda and itemgetter functions
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  behavior list of lists roym 5 443 Jul-04-2021, 04:43 PM
Last Post: roym
  Convert each element of a list to a string for processing tester_V 6 983 Jun-16-2021, 02:11 AM
Last Post: tester_V
  List of lists - merge sublists with common elements medatib531 1 968 May-09-2021, 07:49 AM
Last Post: Gribouillis
  Sort List of Lists by Column Nju 1 704 Apr-13-2021, 11:59 PM
Last Post: bowlofred
  Sume Every 10 element in the list and Divided of Sum quest_ 7 941 Nov-27-2020, 10:58 AM
Last Post: perfringo
  Counting Element in Multidimensional List quest_ 1 670 Nov-25-2020, 10:00 PM
Last Post: quest_
  Adding List Element if Second part of the List Elements are the Same quest_ 3 843 Nov-25-2020, 04:33 PM
Last Post: bowlofred
  Removing element from list squall 6 1,102 Nov-22-2020, 09:34 PM
Last Post: jefsummers
  2d Array adds last element to entire list waiteup 2 639 Nov-19-2020, 08:25 PM
Last Post: bowlofred
  Creating list of lists from generator object t4keheart 1 835 Nov-13-2020, 04:59 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

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