python/lambda_funcs_with_built-ins.py

47 lines
1.5 KiB
Python

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Using a lambda function to filter out odd numbers
even_numbers = filter(lambda x: x % 2 == 0, numbers)
# Convert the filter object to a list
even_numbers_list = list(even_numbers)
print(even_numbers_list)
tuples = [(1, 'banana'), (2, 'apple'), (3, 'orange'), (4, 'grape')]
# Using a lambda function to sort a list of tuples in descending order by the second element
sorted_tuples = sorted(tuples, key=lambda x: x[1], reverse=True)
print(sorted_tuples)
# Using a lambda function to sort a list of tuples in ascending order by the second element
sorted_tuples = sorted(tuples, key=lambda x: x[1], reverse=False)
print(sorted_tuples)
# Using a lambda function to sort a list of tuples in descending order by the first element
sorted_tuples = sorted(tuples, key=lambda x: x[0], reverse=True)
print(sorted_tuples)
# Step 1: Define the list of books
books = [
{"title": "Harry Potter and the Deathly Hallows", "pages": 640},
{"title": "Rich Dad Poor Dad", "pages": 336},
{"title": "The Great Gatsby", "pages": 160},
{"title": "The Hobbit", "pages": 400}
]
# Step 2: Create a custom function
def has_many_pages(book, min_pages=350):
"""Check if the book has more than min_pages."""
return book["pages"] > min_pages
# Step 3: Use filter() with the custom function
filtered_books = filter(lambda book: has_many_pages(book), books)
# Convert the filter object to a list and print
filtered_books_list = list(filtered_books)
print(filtered_books_list)