生成器面试题


生成器面试题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def demo(): # 生成器函数
for i in range(4):
yield i

g=demo() # 生成器

# 生成器表达式
g1=(i for i in g) # 没执行
g2=(i for i in g1)

# 数据类型强转
print(list(g1)) # [0, 1, 2, 3] # 执行了,g1生成器找g取值
print(list(g2)) # [] # g2找g1拿值,g1已经没有值了.所以是空,把g1注释掉,g2就有值了

# 一个生成器里面的能用只能取一次,你不找他要,他也不会给你
# g1=(i for i in g) 没干活,因为他返回了个 生成器
#def g1():
# for i in g:
# yield i
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def add(n,i):
return n+i

def test():
for i in range(4):
yield i

g=test()
for n in [1,10]:
g=(add(n,i) for i in g) # 生成器表达式

# 当遇见这种问题的时候 先将循拆开
# for循环套生成器表达式
# n = 1
# g=(add(n,i) for i in g) # test()
# n = 10
# g=(add(n,i) for i in g) # (add(n,i) for i in g)

# 2 带入方程
# g=(add(n,i) for i in test())
# g=(add(n,i) for i in (add(10,i) for i in test()))
# n = 10
# g=(add(n,i) for i in (add(10,(0,1,2,3))
# n = 10
# g=(add(10,i) for i in (10,11,12,13))
# 20,21,22,23
print(list(g)) # 开始执行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def add(n,i):
return n+i

def test():
for i in range(4):
yield i

g=test()
for n in [1,10,5]:
g=(add(n,i) for i in g) # 生成器表达式

# n = 1
# g=(add(n,i) for i in test())
# n = 10
# g=(add(n,i) for i in (add(n,i) for i in test()))
# n = 5
# g=(add(n,i) for i in (add(n,i) for i in (add(n,i) for i in test())))
# g=(add(n,i) for i in (add(n,i) for i in (add(n,i) for i in (0,1,2,3))))
# g=(add(n,i) for i in (add(n,i) for i in (5,6,7,8)))
# g=(add(n,i) for i in (10,11,12,13)
# 15,16,17,18
print(list(g)) # 开始执行