Last active
July 7, 2022 22:54
-
-
Save onelharrison/517d6d90cccfeba150a194e55d138362 to your computer and use it in GitHub Desktop.
Code snippet showing the use of anonymous functions in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from collections import namedtuple | |
| Person = namedtuple("Person", ["name", "age"]) | |
| if __name__ == "__main__": | |
| people = [ | |
| Person("Marie Curie", 66), | |
| Person("Katherine Johnson", 101), | |
| Person("Ada Lovelace", 36), | |
| ] | |
| first_names = list(map(lambda p: p.name.split(" ")[0], people)) | |
| print(first_names) # ["Marie", "Katherine", "Ada"] | |
| # Filter the list to only people with name starting with 'A' and print it | |
| people_with_names_starting_with_a = list(filter(lambda p: p.name.startswith("A"), people)) | |
| print(people_with_names_starting_with_a) | |
| # Sort the list by name and print it | |
| print(sorted(people, key=lambda p: p.name)) | |
| # Sort the list by age and print it | |
| print(sorted(people, key=lambda p: p.age)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment