gpt4 book ai didi

Python 列表理解。通过重复调用函数直到返回预定义值来生成列表

转载 作者:太空宇宙 更新时间:2023-11-03 18:45:14 24 4
gpt4 key购买 nike

我想通过重复调用函数直到函数返回预定义值来生成列表。

myList = [i,r = foo() while i==0]

myList = [r1, r2, r3, r4...] as long as returned i value is == 0

有没有办法使用列表理解来做到这一点?

最佳答案

def stop_iteration():
raise StopIteration

如果foo()是一个生成器:

myList = list((i,r) if i != 0 else stop_iteration() for (i,r) in foo())

其他:

def foo_generator():
i,r = foo()
while i != 0:
yield i,r
i,r = foo()

myList = list(foo_generator())

关于Python 列表理解。通过重复调用函数直到返回预定义值来生成列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19687253/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com