Python Iterators, Generators, and Lambda: Lazy Evaluation and Functional Tools
About the iterative
The questions in this article can also be addressedPython Foundation: Syntax: Data Structure and File Processing、Python For Object and Decorator: Classes, Inheritance, Policy and ClosedHow the concept of a relatively close read together is developed in different contexts.
Invertable objects and anipher
Reversible objectsIt means that it's done. __iter__() The object of the method. In short, it's an object that can be repeated, that is, it can be used. for Cycle through objects. Common iterative objects include lists, groups, strings, dictionaries, collections, etc.
The object must be an iterative object __iter__() Method, method returns oneOrganisationI'm sorry. When used for When you recycle an iterative object, you actually call the object first __iter__() method to get an iterative device, and then access the elements one by one through an iterative device.
The anecdote is a special object, and it's achieved. __iter__() and __next__() Method (and therefore an iterative object can also be considered).__iter__() Method returns the iterative device itself, and __next__() Method to return the next element of the iterative. When there are no more elements,__next__() The way it's going to be thrown out. StopIteration Unusual.
Like the effect of the code.
my_list = [1, 2, 3] # 获取列表的迭代器 iterator = iter(my_list)使用 next() 函数逐个获取元素
print(next(iterator)) # 输出 1 print(next(iterator)) # 输出 2 print(next(iterator)) # 输出 3
再次调用 next() 会抛出 StopIteration 异常
try: print(next(iterator)) except StopIteration: print("已经没有更多元素了")
For the reference for Cycles functions, and the iterative and iterative objects are important, and many functions are developed on the basis of the iterative objects and are important for their realization.
Intersectional Relevant Functions
map Functions
map function is applied to each element of an iterative object and returns a new iterative device, the element of which is the result of each element of the original avoidable object being processed by the specified function. Its basic grammar is as follows:
map(function, iterable, ...)
function: This is the function to be applied, it will be applied toiterable- Every element of it.iterable: This is one or more iterative objects, such as lists, groups of elements, collections, etc. If you can enter multiple, it is possible to enter several, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, many, others, others, others, others, others, others, and others, others, others, and others.functionThe same number of parameters as the number of reversible objects must be acceptable. Otherwise, it would be a mistake.
A simple example
# 定义一个将元素平方的函数 def square(x): return x ** 2numbers = [1, 2, 3, 4, 5]
使用 map 函数将 square 函数应用到 numbers 列表的每个元素上
squared_numbers = map(square, numbers)
此时返回 map 对象,无法直接打印,需要转换回我们熟悉的数据结构上
将 map 对象转换为列表
result = list(squared_numbers) print(result) # 输出: [1, 4, 9, 16, 25]
About map Function We use often lambda function to simplify the related issues, as follows:
numbers = [1, 2, 3, 4, 5]
# map 函数自身会帮助我们把各个元素传入给函数的,lambda仅仅用于定义函数
squared_numbers = map(lambda x: x ** 2, numbers)
result = list(squared_numbers)
print(result) # 输出: [1, 4, 9, 16, 25]
Deals with multiple iterative objects simultaneously map And very naturally.
numbers1 = [1, 2, 3] numbers2 = [4, 5, 6] # 定义一个将两个元素相加的函数 def add(x, y): return x + y
result = map(add, numbers1, numbers2) print(list(result)) # 输出: [5, 7, 9]
filter Functions
filter Function serves to filter elements in an iterative object, leaving only those that return the specified function True and returns a new iterative. Its basic grammar is as follows:
filter(function, iterable)
function: This is a filter function that accepts a parameter and returns a boolean value. If BackTrue, the element will be retained; if returnedFalse, the element will be filtered out.iterable: This is an iterative object to filter, such as lists, groups, collections, etc.
The overall grammar rule and map The function is very similar, and we need only one more example.
# 定义一个判断元素是否为偶数的函数 def is_even(x): return x % 2 == 0numbers = [1, 2, 3, 4, 5, 6]
使用 filter 函数过滤出偶数
even_numbers = filter(is_even, numbers)
将 filter 对象转换为列表
result = list(even_numbers) print(result) # 输出: [2, 4, 6]
Generator
yield Keywords for a labelgenerator ♪ When a function contains yield So he automatically becomes a generator function and life cycle and character changes.
yield The core of the keyword - “Pause and hand over”
- Normal Functions (
return)"Just like you read 20 episodes of the season and told your friend I'm finished." You only have one option to finish all the stories in one shot. - Generator Function (
yield): Just like you look at a episode and then press the Pause and Hand over button. You give the remote control to your friend, and he goes to see something else. When he comes back to watch, you play him the next episode from where he's just suspended.
yield That's it."Pause and hand over. It did two very important things:
- Hand over value: will
yieldThe later expression results as the return value for this iterative period. - Pause Functions: the performance status of the function (including the value of all local variables) isFreezefunction " Go to sleep" and wait for the next wake-up call.
When a function contains yield And it changed completely:
- Call:
my_generator = my_func()No function will be executed. It just created and returned one.Generator ObjectI'm sorry. This object is like a list of to-dos, which records the code of the function and its current status. - First time in an iterative fashion: When you go through this generator for the first time (e.g., with
for) , function starts until the first one is encounteredyield。 - I met him.
yieldTime: Function HandoveryieldThe value in the back, thenTime out immediately., all internal status is saved. - Next time it's an iterative one.: Function from last pauseAwakening.Continue until you meet the next one.
yield。 - Circumpolarally: This process continues until the function is performed (no more code) or a single one is encountered
returnstatement.
Since... yield It's the lead, that. return Is it still working?
Yes, but its role has changed. In the generator function,return The effect is...Early termination generator。
When the generator function executes one return When a statement is made, it will stop and trigger a StopIteration Unusual. This anomaly can be captured.return The value in the back will be this unusual. value attribute.
This is a relatively advanced use, usually used to transmit an additional "end state" or "misinformation" to the generator's users.
That's using the structures below to make unusual seizures.
def generator_with_return(n): i = 0 while i < n: yield i i += 1 return "我处理完了所有数字!" # <-- return 在这里创建生成器
gen = generator_with_return(3)
手动迭代,以便捕获 StopIteration
while True: try: value = next(gen) # next() 函数获取下一个值 print(f"从生成器拿到: {value}") except StopIteration as e: print(f"生成器结束了!") print(f"它 return 的值是: {e.value}") # <– 在这里获取 return 的值 break
In usegenerator, and then select the for It's a loop to read. He'll do it automatically.StopIteration The problem is that it ends naturally by going through all the elements.
The generator can only be repeated once
Other
Sort FunctionskeyParameters
In the most common sorted() function key We've decided what we use as a basis for sorting, in many cases, into. sorted() The function is often not a list but a complex dictionary, so we need to specify which key to use for sorting.
students = [
{'name': 'Alice', 'age': 20},
{'name': 'Bob', 'age': 18},
{'name': 'Charlie', 'age': 22}
]
# 按照年龄从小到大排序
sorted_students = sorted(students, key=lambda student: student['age'])
print(sorted_students)
key The actual working principle of the parameters is not that simple. He is a function.sorted Function iterable Each element of this calls this key function, then by key function to compare the size of the element, rather than directly to the element itself.
In this code, we have to consider the question of the code.key It's a function that fits the usual definition.lambdaFunction, we'reiterable Each element of this calls thislambdafunction, get a value for sorting, here's thelambdaFunction to extract the key pairs entered into the functionageThe value of the key, that's what makes it understandable.
lambdaFunctions
lambda function is a simple anonymous function in Python that can be defined and used temporarily where the function object is needed, without the need to define a full function in a visible manner.lambda KeywordsCreate small, one-time, anonymous functionsI'm sorry. Its basic grammar is as follows:
lambda 参数列表: 表达式
- List of Parameters: This is the parameter that is passed to the function, with zero or more parameters, separated by commas.
- Expression: This is the value that the function is going to return,
lambdafunction can only contain one expression, and the result of that expression will be returned automatically.
This is the right place. lambda function is easily understood as " sorting function " key Why is it often used in Parameters: it can create simple functions quickly without redefinition and maintenance in the front.
Multiparameterslambda It's natural to define functions.
lambda x, y: x < y
Like normal functions,lambda function can be used to return the function value (which can be called after it is called as normal), thus achieving some interesting functions, such as:
def multiplier(factor): return lambda x: x * factordouble = multiplier(2) triple = multiplier(3)
print(double(5)) # 输出 10 print(triple(5)) # 输出 15
- Title: Python Iterators, Generators, and Lambda: Lazy Evaluation and Functional Tools
- Author: Hyacehila
- Created at : 2025-04-19 11:53:29
- Link: https://hyacehila.github.io//blog/2025/04/19/python-iterators-generators-lambda-learning-notes/
- License: This work is licensed under CC BY-NC-SA 4.0.