Sort list of lists ascending and then descending
L = [['a',1], ['a',2], ['a',3], ['b',1], ['b',2], ['b',3]]
L.sort(key=lambda k: (k[0], -k[1]), reverse=True)
L
now contains:
[['b', 1], ['b', 2], ['b', 3], ['a', 1], ['a', 2], ['a', 3]]
How to sort a list of lists by one element ascending and another descending
If I understand correctly you want to sort by the second element (number) descending and by the first element (letter) ascending alphabetically.
This should get what you're looking for:
mylist = list=[['a', 5], ['l', 2], ['u', 1], ['t', 1], ['q', 1], ['o', 1], ['e', 1]]
sorted_list = sorted(mylist, key = lambda x:(-x[1], x[0]))
print(sorted_list)
#[['a', 5], ['l', 2], ['e', 1], ['o', 1], ['q', 1], ['t', 1], ['u', 1]]
We use the key
argument to sorted
to define how to sort the list. In this case, we pass in a lambda function lambda x: (-x[1], x[0])
as the key function. The "trick" here is that we pass in the negative of x[1]
(negative of the number) so that it sorts by the number descending. The second element of the tuple x[0]
is the character, which will serve to break ties for list elements with the same number value.
Sort a list of lists using descending order, and then if there is a tie breaker, use descending order on another index in python
It is because you are applying a negation (-
) on a tuple a string. Using sorted
function, you can use reverse=True
to sort the array in descending order.
sorted(master_list, key=lambda x: (x[1], x[0]), reverse=True)
Sort List of dicts first in ascending order of a key and then in descending order of another key
If you are sorting by number, you can just multiply by -1
to reverse the order:
>>> a = [{"x" : 5 , "y" : 7} , {"x" : 4 , "y" : 3} , {"x" : 4 , "y" : 7}]
>>> sorted(a , key=lambda k: (k['x'] , k['y'] * -1))
[{'x': 4, 'y': 7}, {'x': 4, 'y': 3}, {'x': 5, 'y': 7}]
You can also add -
before the variable and it will work the same way as multiplying by -1
:
>>> sorted(a , key=lambda k: (k['x'] , -k['y']))
[{'x': 4, 'y': 7}, {'x': 4, 'y': 3}, {'x': 5, 'y': 7}]
How to sort a list in descending order for the first criteria and ascending order for the second criteria?
Try this way, maybe that helps:
It works because your items are tuples so we use the tricks to sort them by desc/asceding order differently.
So the first will be descending order, and 2nd ascending as it shown.
Notes - please don't use Python built-in as the variable names.
>>> L = [(99, 41), (85, 33), (99, 28)]
>>> sorted(L, key=lambda x: (-x[0], x[1]))
[(99, 28), (99, 41), (85, 33)]
>>> A = [(12, 22), (13, 33), (12, 12), (13, 3)]
>>> A.sort(key=lambda x: (-x[0], x[1])) # in-place sort
>>>
>>> A
[(13, 3), (13, 33), (12, 12), (12, 22)]
One liner function for sorting a string list of lists in ascending, descending order based on varying criteria in python
In addition to all of the other fine answers here, you can also write your own ordering class:
from functools import total_ordering
@total_ordering
class MyOrdering(object):
def __init__(self, value):
self.value = value
def __eq__(self, other):
return other.value == self.value
def __lt__(self, other):
for i in [0, 2, 4]:
if self.value[i] != other.value[i]:
return self.value[i] < other.value[i]
for i in [1, 3]:
if self.value[i] != other.value[i]:
return self.value[i] > other.value[i]
return False
And then you can sort using the MyOrdering class as your key function:
outer_list.sort(key=MyOrdering)
How to sort a list of lists based on the length of the inner lists, but if two inner lists are equal then sort based on first element of inner list
you can define rule in key
in sort function on the order of sorting
l =[[1, 2, 3], [2, 1], [3, 2], [4, 5, 1], [5]]
l.sort(key=lambda x:[len(x), x[0]], reverse=True)
print(l)
output
[[4, 5, 1], [1, 2, 3], [3, 2], [2, 1], [5]]
How to do a multi level sort on list of lists in Python?
You changed the expected output, this would be the solution for that:
lst.sort(key=lambda x: (-int(x[1]), x[0]), reverse=True)
#[['baby', '10'], ['apple', '10'], ['baby', '20'], ['candy', '30']]
This was the answer before the question was edited and seperates the entries before sorting them:
print(*zip(sorted([x[0] for x in lst], reverse=True), sorted([x[1] for x in lst])))
# ('candy', '10') ('baby', '10') ('baby', '20') ('apple', '30')
Related Topics
Pelican 3.3 Pelican-Quickstart Error "Valueerror: Unknown Locale: Utf-8"
How to Run an External Command Asynchronously from Python
Windows Scipy Install: No Lapack/Blas Resources Found
Is Shared Readonly Data Copied to Different Processes for Multiprocessing
Keyboard Interrupts with Python's Multiprocessing Pool
How to Read Realtime Microphone Audio Volume in Python and Ffmpeg or Similar
How to Execute Python File in Linux
Curses-Like Library for Cross-Platform Console App in Python
Installing Python Modules on Ubuntu
Python/Ipython Importerror: No Module Named Site
Prevent Sleep Mode Python (Wakelock on Python)
Is Shared Readonly Data Copied to Different Processes for Multiprocessing
How to Automatically Install Required Packages from a Python Script as Necessary
How to Build 32Bit Python 2.6 on 64Bit Linux
Run a Linux System Command as a Superuser, Using a Python Script