• 1
    数据输入输出
    • 任务
  • 2
    条件语句
    • 任务
  • 3
    for循环
    • 任务
  • 4
    字符串
    • 任务
  • 5
    while循环
    • 任务
  • 6
    列表
    • 任务
  • 7
    二维数组
    • 任务
  • 8
    字典
    • 任务
  • 9
    集合
    • 任务
  • 10
    函数与递归
    • 任务
  • к

课程 10. Functions and recursion

难度:

任务«过滤数字列表,根据条件筛选»

💻 Python
在电子产品商店中,对商品提供额外折扣,这些商品的价格同时是偶数且能被3整除,并刊登在广告手册中。
rn
编写一个程序,接收商品价格列表,并仅显示那些既是偶数又能被3整除的价格。使用lambda函数进行数据过滤。

输入格式

一行由空格分隔的数字——商品的价格(以卢布计)

输出格式

合适的价格按升序排列,并用空格分隔。如果没有合适的价格,则显示空行

示例

输入

12 15 18 20 24 30 35 36

输出

12 18 24 30 36

提示

Lambda functions in Python: A Complete Guide

Lambda functions in Python, also known as anonymous functions, are small, usually one-time functions that are defined using the lambda keyword. Their key feature is that they can contain only one expression and do not have a proper name, which makes them an ideal tool for tasks where a full-fledged definition of a function via def would be redundant. Lambda functions are often used to create short functions on the fly, for example, as arguments to other, higher-level functions.

Main characteristics of lambda functions

  • Anonymity: Lambda functions do not have a name, like functions defined via def. They are function objects that can be assigned to a variable, but this is not their main purpose.
  • One expression: A Lambda function can contain only one single expression. It is important to understand that the result of calculating this expression is automatically returned. You don't need to use the return keyword. This is their main limitation - you cannot place multiple commands, loops, or complex conditional constructions in lambdas.
  • Conciseness: The main advantage of lambda functions is the brevity of the code. They allow you not to litter the namespace with one-time functions and make the code more compact in certain situations.

Syntax of lambda functions

The syntax of the lambda function is simple and elegant:

lambda arguments: expression

  • lambda is the keyword.
  • arguments are one or more arguments separated by commas (just like in a regular function).
  • : a colon separating arguments from expressions.
  • expression - one expression, the result of which will be returned.

Examples of using lambda functions

1. The simplest lambda function

Although lambda functions can be assigned to variables, this is often considered not the best practice. If the function needs a name, it is better to use def. Nevertheless, it is useful for demonstration purposes.

Creating a lambda function that returns the square of a number:

square = lambda x: x ** 2
print(square(5)) # Output: 25

A useful tip: Code verification tools (linters) often mark such an assignment as an antipattern. If you want to give a function a reusable name, a standard definition is preferable.:

def square(x):
return x ** 2

2. Lambda function with multiple arguments

Creating a lambda function that adds two numbers together:

sum = lambda a, b: a + b
print(sum(3, 4)) # Output: 7

3. Using lambda functions with built-in functions

This is where lambda functions really reach their potential. They are ideal for passing map(), filter(), sorted() and others as arguments.

Usage with map()

The map() function applies the specified function to each element of the iterated object and returns an iterator with the results.

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

A useful tip: For simple operations, as in this example, list comprehensions are a more "Pythonic" and often more readable way:

square_alt = [x ** 2 for x in numbers]
print(square_alt) # Output: [1, 4, 9, 16, 25]

Use with filter()

The filter() function returns an iterator consisting only of those elements for which the passed function returned True.

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

A useful tip: Here, too, listing with a condition would be a great alternative.:

even_alt = [x for x in numbers if x % 2 == 0]
print(even_alt) # Output: [2, 4, 6, 8, 10]

Usage with sorted()

The sorted() function returns a new sorted list. Lambda functions are indispensable here for specifying a complex sorting key without having to define a separate function.

students = [("Alice", 25), ("Bob", 22), ("Charlie", 23)]
# Sorting the list of tuples by the second element (age)
sorted students = sorted(students, key=lambda x:x[1])
print(sorted students)
# Output: [('Bob', 22), ('Charlie', 23), ('Alice', 25)]

A useful tip: This is one of the best examples of using lambda. It would be unnecessary to create a separate function def get_age(student): return student[1] just for this one sort.

4. Lambda functions inside other functions (Closures)

Lambda functions can be returned from other functions. This is a powerful technique called closure, where an internal function "remembers" the context in which it was created.

def multiplication(n):
# This function returns another function (lambda)
return lambda x: x * n

# Creating functions based on the multiplication
factory multiplication_2 = multiplication(2) # Here n=2 "remembered"
multiplication_3 = multiplication(3) # Here n=3 "remembered"

print(multiplication to_2(5)) # Output: 10
print(multiplication to_3(5)) # Output: 15

In this example, lambda x:x *n "captures" the value of the variable n from the external function multiplication and stores it for subsequent calls.

main.py
测试 1
测试 2
测试 3
测试 4
测试 5
测试 6
测试 7
测试 8
测试 9
测试 10
开发者解答

🎉 恭喜! 🎉

你出色地完成了任务!这是一个不小的挑战,但你找到了正确答案。你离编程大师又近了一步!继续保持,每一步都让你更强大。

AD

广告

red-snake blue-snake green-snake

正在运行代码...

AI助手

你好!我是你的编程助手。随时向我提问关于 Python 的问题——我可以解释函数、方法,并帮助你完成当前任务!