我正在研究 python 中生成器的主题,无法处理一项任务。
重点是:您需要实现一个生成器,它接受 2 个非递减序列,将其组合成 1 个非递减序列并返回。
我明白怎么用一个函数来写,但是我不知道怎么通过“yield”来实现。
这是我的函数的代码:
def merge_lists(lst1, lst2):
res = []
i1, i2 = 0, 0
while i1 < len(lst1) and i2 < len(lst2):
el1, el2 = lst1[i1], lst2[i2]
res.append(el1)
i1 += 1
res.append(el2)
i2 += 1
res.extend(lst1[i1:])
res.extend(lst2[i2:])
return res
我很乐意在编写代码和解释解决方案方面获得帮助。
最佳答案
代码/算法:
def merge_lists(lst1, lst2):
i = j = 0
while i < len(lst1) and j < len(lst2):
if lst1[i] <= lst2[j]:
yield lst1[i]
i += 1
else:
yield lst2[j]
j += 1
while i < len(lst1):
yield lst1[i]
i += 1
while j < len(lst2):
yield lst2[j]
j += 1
解释:
我们首先将变量 i
、j
初始化为零,它们表示列表 lst1
和 lst2
中的索引分别。
在第一个 while 循环中,我们随后检查 lst1
和 lst2
中较小的元素,例如。如果较小的是 lst1[i]
那么我们yield
元素 lst1[i]
并增加索引 i
否则我们yield
元素 lst2[j]
并递增索引 j
循环的其余部分不言自明。
在其他 while 循环中,我们检查 lst1
和 lst2
中是否还有剩余的元素,如果有,我们就yield
元素也。
示例:
lst1 = list(range(0, 10)) # lst1 is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
lst2 = list(range(10, 21)) # lst2 is [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
for num in merge_lists(lst1, lst2): # -- loop through the generator
print(num, end=" ") #--> use the results on demand
结果:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 # --> combined non declining sequence
关于python - 合并序列的生成器的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61010395/