开发者

Python transform while-loop into a generator function

I want to replace and optim开发者_如何转开发ize an extensively used while-loop that generates list values from an input list. How can this be accomplished with iter, itertools, a generator function or something else? The following example code is for illustration only:

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


You can do it with a generator. It yields the next value every time you call "next" on it.

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()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜