一
# Initialize the list my_list = [1, 3, 6, 10] # square each term using list comprehension # Output: [1, 9, 36, 100] [x**2 for x in my_list] # same thing can be done using generator expression # Output: <generator object <genexpr> at 0x0000000002EBDAF8> (x**2 for x in my_list)
二
# Intialize the list my_list = [1, 3, 6, 10] a = (x**2 for x in my_list) # Output: 1 print(next(a)) # Output: 9 print(next(a)) # Output: 36 print(next(a)) # Output: 100 print(next(a)) # Output: StopIteration next(a)
例子1
#!/usr/bin/python3 #coding=utf-8 def my_gen(): n = 1 print('This is printed first, n= ', n) # Generator function contains yield statements yield n n += 1 print('This is printed second, n= ', n) yield n n += 1 print('This is printed at last, n= ', n) yield n
输出
>>> # It returns an object but does not start execution immediately. >>> a = my_gen() >>> # We can iterate through the items using next(). >>> next(a) This is printed first, n = 1 1 >>> # Once the function yields, the function is paused and the control is transferred to the caller. >>> # Local variables and theirs states are remembered between successive calls. >>> next(a) This is printed second, n = 2 2 >>> next(a) This is printed at last, n = 3 3 >>> # Finally, when the function terminates, StopIteration is raised automatically on further calls. >>> next(a) Traceback (most recent call last): ... StopIteration >>> next(a) Traceback (most recent call last): ... StopIteration
例子2
# A simple generator function def my_gen(): n = 1 print('This is printed first') # Generator function contains yield statements yield n n += 1 print('This is printed second') yield n n += 1 print('This is printed at last') yield n # Using for loop for item in my_gen(): print(item)
输出
This is printed first 1 This is printed second 2 This is printed at last 3
例子3
反转字符串的生成器
def rev_str(my_str): length = len(my_str) for i in range(length - 1,-1,-1): yield my_str[i] for char in rev_str("hello"): print(char)
输出
o
l
l
e
h