As one of the acknoledged reviewers of the Manning book Python How-To, I have decided to make a YouTube video, based on a part of the book, mentioning Lambda Expressions.
The video is here, and the code I have used is pretty much this one:
1 2 3 4 5 6 |
a = lambda x: x * 2 print(a(3)) #syntax error if you use RETURN keyword: a = lambda x: return x * 2 print(a(3)) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
tasks = [ {'title': 'A', 'desc': 'First Letter', 'urgency': 6}, {'title': 'B', 'desc': 'Second Letter', 'urgency': 5}, {'title': 'C', 'desc': 'Third Letter', 'urgency': 2} ] def using_urgency_level(task): return task['urgency'] tasks.sort(key=using_urgency_level, reverse=True) print(tasks) def using_urgency_level(task): return task['urgency'] tasks.sort(key=lambda x: x['urgency'], reverse=False) print(tasks) using_urgency_level = lambda x: x['urgency'] tasks.sort(key=using_urgency_level, reverse=True) print(tasks) |
1 2 3 4 5 6 7 8 9 10 |
integers = [-4, 3, 7, 0, -6] sorted_abs = sorted(integers, key=lambda x: abs(x)) print(sorted_abs) print(integers) #pythonic way: integers = [-4, 3, 7, 0, -6] sorted_abs = sorted(integers, key=abs) print(sorted_abs) print(integers) |
1 2 3 |
scores = [(1, 2, 3), (4, 4, 5), (2, 3, 4), (1, 2, 7)] max(scores, key=lambda x: x[0] + x[1] + x[2]) max(scores, key=sum) |
If you are interested in buying Manning books, you can use this code for 40% discount on all their products: watchcui40