将Python的while循环转换为生成器函数

1 投票
1 回答
2686 浏览
提问于 2025-04-17 01:05

我想要替换和优化一个经常使用的 while 循环,这个循环是用来从一个输入列表生成值的。请问我可以用 iter、itertools、生成器函数或者其他方法来实现吗?下面的示例代码只是用来说明问题的:

thislist = [2, 8, 17, 5, 41, 77, 3, 11]

newlist = []

index = 0
listlength = len(thislist)

while index < listlength:
    value = 0
    while thislist[index] >= 0:
        value += thislist[index]
        value += 2 * value
        index += 1
    value += thislist[index]
    index += 1
    newlist.append(value)

print newlist

1 个回答

0

你可以使用生成器来实现这个功能。每次你调用它的“next”时,它会返回下一个值。

def my_gen(data):
    for index in range(0, len(data)-1):
        value = data[index]
        value += 2 * value
        #etc
        yield value

my_list = [2, 8, 17, 5, 41, 77, 3, 11]
x = my_gen(my_list)
print x.next()
print x.next()

撰写回答