Files

1.4 KiB

id, source_exercise_id, title, section, source_path, source_repo, source_commit, student_visible_solution, has_private_solution, skip
id source_exercise_id title section source_path source_repo source_commit student_visible_solution has_private_solution skip
practical-python-7.6 7.6 Sorting on a field with lambda 7.2 Anonymous Functions and Lambda 07_Advanced_Topics/02_Anonymous_function.md https://github.com/dabeaz-course/practical-python 93dca856b41c61a0a0f85ae334116e4c125629ea false false false

Exercise 7.6: Sorting on a field with lambda

Source: Practical Python Programming, 07_Advanced_Topics/02_Anonymous_function.md.

Exercise 7.6: Sorting on a field with lambda

Try sorting the portfolio according the number of shares using a lambda expression:

>>> portfolio.sort(key=lambda s: s.shares)
>>> for s in portfolio:
        print(s)

... inspect the result ...
>>>

Try sorting the portfolio according to the price of each stock

>>> portfolio.sort(key=lambda s: s.price)
>>> for s in portfolio:
        print(s)

... inspect the result ...
>>>

Note: lambda is a useful shortcut because it allows you to define a special processing function directly in the call to sort() as opposed to having to define a separate function first.

Contents | Previous (7.1 Variable Arguments) | Next (7.3 Returning Functions)

关联来源