Python 合并序列的生成器出现问题
我正在研究python中生成器的主题,无法处理一项任务 要点是:您需要实现一个生成器,它接受2个非递减序列,将其组合成1个非递减序列并返回它 我知道如何用函数编写它,但我不知道如何通过“yield”实现它 以下是我的函数代码:Python 合并序列的生成器出现问题,python,Python,我正在研究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[i
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合并列表(lst1、lst2):
res=[]
i1,i2=0,0
当i1
我很乐意在编写代码和解释解决方案方面得到帮助
import itertools
itertools.chain.from_iterable([range(10), range(20, 30)])
# Should get your work done.
# Or, in your case
itertools.chain.from_iterable([lst1, lst2])
请访问以获取更多有用的生成器。代码/算法:
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
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
结果:
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
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
a=[9,7,5,3]
b=[8,6,4,2]
def合并(l1、l2):
i1=0
i2=0
而i1