How to sort with lambda in Python

In Python, I'm trying to sort by date with a lambda. I can not understand my error message. Message:

<lambda>() takes exactly 1 argument (2 given) 

I have a line

 a = sorted(a, lambda x: x.modified, reverse=True) 
+134
python lambda
Sep 22 '10 at 5:46 april
source share
3 answers

Using

 a = sorted(a, key=lambda x: x.modified, reverse=True) # ^^^^ 

In Python 2.x, the sorted function takes its arguments in the following order:

 sorted(iterable, cmp=None, key=None, reverse=False) 

therefore, without key= function you pass in will be considered a cmp function that takes 2 arguments.

+264
Sep 22 '10 at 5:48
source share
 lst = [('candy','30','100'), ('apple','10','200'), ('baby','20','300')] lst.sort(key=lambda x:x[1]) print(lst) 

The following will be printed:

 [('apple', '10', '200'), ('baby', '20', '300'), ('candy', '30', '100')] 
+5
Mar 09 '19 at 18:18
source share

Python lists have two built-in ways to sort data:

 sort() — A method that modifies the list in-place sorted() — A built-in function that builds a new sorted list from an iterable 

Based on your requirements, you can choose one of these two:

if you want to keep the original list, you can use the sorted function or, if you do not need the original list, you can use the sort function.

Before we start sorting or sorting, we need to understand the lambda.

A lambda is an anonymous function, and an anonymous function is a function that is defined without a name, this post seems to explain it pretty well.

https://www.programiz.com/python-programming/anonymous-function

Lambda functions are convenient for calling in-line, because they have only one expression, which is evaluated and returned. They have the syntax for lambda like this:

lambda arguments: expression

let's see how to use a sorted function:

 student_tuples = [('john', 'A', 15),('jane', 'B', 12),('dave', 'B', 10),] sorted(student_tuples, key=lambda student: student[2]) 

output: [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Here we see that the list of student_tuples with tuples is sorted based on the key parameter, provided that student [2].

0
Jul 22 '19 at 4:43
source share



All Articles