Python 将负载平衡功能转换为发电机

Python 将负载平衡功能转换为发电机,python,generator,Python,Generator,我正在尝试创建一个小的负载平衡函数,它将接收一个有序数字列表(这些数字将是字符串长度)并输出负载平衡块。我们的想法是从索引为0(最小字符串长度)的块开始,然后向其添加索引-1(最长字符串长度)。我们重复这个过程,直到字符串长度用完(存储在列表\u ordered中),这样每个块都有一个所需的块大小 无论如何,下面的函数工作正常,但不可精确扩展,因为我们正在列表res中存储所有数据;我的问题是,考虑到我想要的和下面的代码,你能帮我把这个函数转换成一个生成器吗 谢谢 def chunk_genera

我正在尝试创建一个小的负载平衡函数,它将接收一个有序数字列表(这些数字将是字符串长度)并输出负载平衡块。我们的想法是从索引为0(最小字符串长度)的块开始,然后向其添加索引-1(最长字符串长度)。我们重复这个过程,直到字符串长度用完(存储在
列表\u ordered
中),这样每个块都有一个所需的
块大小

无论如何,下面的函数工作正常,但不可精确扩展,因为我们正在列表
res
中存储所有数据;我的问题是,考虑到我想要的和下面的代码,你能帮我把这个函数转换成一个生成器吗

谢谢

def chunk_generator_load_balanced(list_ordered,chunk_size):
    n_chunks=ceil(len(list_ordered)/chunk_size)
    res=[]
    direction_chunks={}
    for i in range(n_chunks):
        res.append([])
        direction_chunks[i]=True
    chunk_index=0
    while list_ordered:
        if direction_chunks[chunk_index]:
            chunk_val=list_ordered.pop(0)
            direction_chunks[chunk_index]=False
        else:
            chunk_val=list_ordered.pop(-1)
            direction_chunks[chunk_index]=True
        res[chunk_index].append(chunk_val)
        if chunk_index==n_chunks-1: chunk_index=0
        else: chunk_index+=1
    return res

if __name__ == '__main__':
    list_keys=[i for i in range(50)]
    a=chunk_generator_load_balanced(list_keys,10)


为什么不在chunk\u generator\u load\u balanced函数中使用yield而不是return呢

我的意思是:

def chunk_generator_load_balanced(list_ordered,chunk_size):
n_chunks=ceil(len(list_ordered)/chunk_size)
res=[]
direction_chunks={}
for i in range(n_chunks):
    res.append([])
    direction_chunks[i]=True
chunk_index=0
while list_ordered:
    if direction_chunks[chunk_index]:
        chunk_val=list_ordered.pop(0)
        direction_chunks[chunk_index]=False
    else:
        chunk_val=list_ordered.pop(-1)
        direction_chunks[chunk_index]=True
    res[chunk_index].append(chunk_val)
    if chunk_index==n_chunks-1: chunk_index=0
    else: chunk_index+=1
yield res

实际上,这个想法是消除中间值res,产生
res
res
块实际上不会改变任何东西,因为所有中间值都需要在while循环中预先创建。。。。我的目标是以某种方式将while循环转换为一个生成器,该生成器可以当场创建块,而无需将它们保存在内存中。