Python's list comprehension + generator

list comprehension

That is, List Comprehensions, also called list generation, is a very simple but powerful built-in python built-in generation that can be used to create lists.

Its structure is to contain an expression in square brackets, then a for statement, and then zero or more for or if statements. The expression in it can be any type of object, and the return result is a new list (otherwise it is called a list comprehension).

Similarly, there are dictionary derivation and set derivation.

>>> [x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]

也可以循环嵌套
>>> [m +n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']

迭代对象可以加上筛选条件
>>> [x if x % 2 == 0 else -x for x in range(1, 11)]
[-1, 2, -3, 4, -5, 6, -7, 8, -9, 10]
# 用字典推导式快速对换一个字典的键和值
{
    
    v: k for k, v in my_dict.items()}

# 集合推导式区别于列表推导式的地方是{}
squared = {
    
    x**2 for x in [1, 2, 3]}
print(squared)
# print out: {1, 4}

Builder

Generator is a mechanism in python that calculates while looping.

A generator is a special type of function that yields one value at a time. Think of it as a resumable function. Calling this function will return a Generator that can be used to generate continuous x values. Simply put, during the execution of the function, the yield statement will return the value you need to the place where the generator is called, and then exit the function, and the next call will generate When the generator function is executed, it will resume from the place where it was interrupted last time, and all variable parameters in the generator will be saved for the next use.

All the data in the list is stored in memory. If there is a lot of data in it, and we only need to access the first few elements, the space occupied by most of the elements behind will be wasted. The generator is to make the list calculated according to a certain algorithm, and we can calculate the subsequent elements while looping, thereby avoiding unnecessary waste of space.

Two ways to create a generator

'''把列表生成式的[]改成(),创建一个生成器'''
>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x00000264E0A49430>

# 通过for循环打印generator里的值
>>> g = (x * x for x in range(4))
>>> for n in g:
...    	print(n)
...
0
1
4
9
'''定义的函数中包含yield关键字时,这个函数就是一个generator函数,调用该函数创建一个对象后,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次中断的地方继续执行'''
def generator_function():
	for i in range(5):
		yield i

for item in generator_function():
	print(item)
'''
print out:
0
1
2
3
4
'''

Guess you like

Origin blog.csdn.net/m0_61251376/article/details/125929293