杰瑞科技汇

python list lambda

Of course! Let's break down how to use lambda functions with Python lists. This is a very common and powerful pattern for writing concise and readable code.

python list lambda-图1
(图片来源网络,侵删)

We'll cover:

  1. What is a Lambda Function? (A quick refresher)
  2. Why Use Lambdas with Lists? (The motivation)
  3. The Main Use Cases:
    • filter(): Selecting items
    • map(): Transforming items
    • sorted(): Sorting items
  4. Alternatives and When to Avoid Lambdas
  5. Putting It All Together

What is a Lambda Function?

A lambda function is a small, anonymous (unnamed) function defined using the lambda keyword. It can take any number of arguments but can only have one expression.

Syntax: lambda arguments: expression

Example: A normal function to square a number:

python list lambda-图2
(图片来源网络,侵删)
def square(x):
  return x * x
print(square(5)) # Output: 25

The same thing as a lambda:

# The lambda function is assigned to a variable 'square'
square = lambda x: x * x
print(square(5)) # Output: 25

You don't have to assign a lambda to a variable. You can use it directly where it's needed.


Why Use Lambdas with Lists?

Lists are collections of data. Often, you need to perform an operation on every item in a list (map), select only certain items (filter), or sort the list based on a specific rule (sorted). Lambdas provide a clean, one-line way to define the simple logic needed for these operations.


The Main Use Cases

Here are the three most common built-in functions that work beautifully with lambdas and lists.

python list lambda-图3
(图片来源网络,侵删)

A. filter(): Selecting Items

The filter() function constructs an iterator from elements of an iterable for which a function returns true. In simple terms, it lets you "filter" a list to keep only the items you want.

  • How it works: filter(function, iterable)
  • The function should return True or False. filter() keeps the items that make the function return True.

Example: Get only the even numbers from a list.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Define a lambda function that returns True if a number is even
is_even = lambda x: x % 2 == 0
# Use filter() with the lambda
even_numbers = list(filter(is_even, numbers))
print(even_numbers)
# Output: [2, 4, 6, 8, 10]

More Concise Version: You can often pass the lambda directly into filter() without assigning it to a variable first.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
# Output: [2, 4, 6, 8, 10]

B. map(): Transforming Items

The map() function applies a given function to each item of an iterable (like a list) and returns a map object (an iterator). You then convert this iterator back to a list. It's used for transforming data.

  • How it works: map(function, iterable)
  • The function is applied to every single item in the iterable.

Example: Square every number in a list.

numbers = [1, 2, 3, 4, 5]
# Use map() with a lambda to square each number
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers)
# Output: [1, 4, 9, 16, 25]

Example: Convert a list of names to uppercase.

names = ["alice", "bob", "charlie"]
uppercase_names = list(map(lambda name: name.upper(), names))
print(uppercase_names)
# Output: ['ALICE', 'BOB', 'CHARLIE']

C. sorted(): Sorting Items

The sorted() function returns a new sorted list from the items in an iterable. The key argument is where a lambda shines. The key is a function that is called on each element before making comparisons.

  • How it works: sorted(iterable, key=function)
  • The function should return a value that sorted() will use for comparison.

Example: Sort a list of tuples by the second element.

points = [(1, 5), (4, 2), (9, 8), (3, 1)]
# The default sort would be by the first element (the x-coordinate).
# We want to sort by the second element (the y-coordinate).
# The lambda tells sorted: "For each item `p`, use `p[1]` as the sorting key."
sorted_points = sorted(points, key=lambda p: p[1])
print(sorted_points)
# Output: [(3, 1), (4, 2), (1, 5), (9, 8)]

Example: Sort a list of dictionaries by a specific key.

students = [
    {'name': 'Alice', 'grade': 85},
    {'name': 'Bob', 'grade': 92},
    {'name': 'Charlie', 'grade': 78}
]
# Sort the list of dictionaries by the value of the 'grade' key
sorted_by_grade = sorted(students, key=lambda s: s['grade'])
print(sorted_by_grade)
# Output: [{'name': 'Charlie', 'grade': 78}, {'name': 'Alice', 'grade': 85}, {'name': 'Bob', 'grade': 92}]

Alternatives and When to Avoid Lambdas

While powerful, lambdas are not always the best choice.

List Comprehensions (Often a Better Alternative for map and filter)

For map and filter, list comprehensions are often considered more "Pythonic" and readable because they are more direct.

filter() with a List Comprehension:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Instead of: list(filter(lambda x: x % 2 == 0, numbers))
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)
# Output: [2, 4, 6, 8, 10]

map() with a List Comprehension:

numbers = [1, 2, 3, 4, 5]
# Instead of: list(map(lambda x: x**2, numbers))
squared_numbers = [x**2 for x in numbers]
print(squared_numbers)
# Output: [1, 4, 9, 16, 25]

Rule of Thumb: Use list comprehensions for simple transformations (map) and filtering (filter). They are generally more readable for these cases.

When to Use a Regular def Function Instead of lambda

You should avoid using a lambda when:

  1. The logic is complex. If your function has if/else statements (other than a ternary operator), loops, or multiple lines of logic, it's too complex for a lambda. Use a def function.
  2. You need to reuse the function. If you plan to use the same logic in multiple places, give it a name with def for better code organization and reusability.
  3. The logic needs a docstring. Lambda functions cannot have docstrings, making them harder to document.

Putting It All Together: A Practical Example

Let's say you have a list of products, and you want to find all products that are in stock and then create a new list with just their names, sorted alphabetically.

products = [
    {'name': 'Laptop', 'price': 1200, 'in_stock': True},
    {'name': 'Mouse', 'price': 25, 'in_stock': False},
    {'name': 'Keyboard', 'price': 75, 'in_stock': True},
    {'name': 'Monitor', 'price': 300, 'in_stock': True},
    {'name': 'Webcam', 'price': 50, 'in_stock': False}
]
# 1. Filter: Get only the products that are in_stock
#    The lambda checks the value of the 'in_stock' key.
in_stock_products = list(filter(lambda p: p['in_stock'], products))
# 2. Map: Extract just the 'name' from each filtered product
#    The lambda takes a product dictionary `p` and returns its name.
product_names = list(map(lambda p: p['name'], in_stock_products))
# 3. Sort: Sort the list of names alphabetically (the default for strings)
#    We don't even need a lambda here, as strings sort alphabetically by default.
sorted_names = sorted(product_names)
print(f"In Stock Products: {in_stock_products}")
# Output: In Stock Products: [{'name': 'Laptop', 'price': 1200, 'in_stock': True}, {'name': 'Keyboard', 'price': 75, 'in_stock': True}, {'name': 'Monitor', 'price': 300, 'in_stock': True}]
print(f"Sorted Names of In-Stock Products: {sorted_names}")
# Output: Sorted Names of In-Stock Products: ['Keyboard', 'Laptop', 'Monitor']

Summary Table

Function Purpose Lambda Example List Comp. Alternative
filter() Select items that meet a condition. list(filter(lambda x: x > 0, numbers)) [x for x in numbers if x > 0]
map() Transform every item in a list. list(map(lambda x: x*2, numbers)) [x*2 for x in numbers]
sorted() Sort a list based on a custom key. sorted(lst, key=lambda x: x['key']) N/A (No direct equivalent)
分享:
扫描分享到社交APP
上一篇
下一篇