gpt4 book ai didi

python - 如何在 Python 的 for 循环中检索剩余的项目?

转载 作者:行者123 更新时间:2023-12-02 16:20:41 26 4
gpt4 key购买 nike

我有一个简单的 for 循环遍历项目列表。在某个时候,我知道它会破裂。我怎样才能退回剩余的元素?

for i in [a,b,c,d,e,f,g]:
try:
some_func(i)
except:
return(remaining_items) # if some_func fails i.e. for c I want to return [c,d,e,f,g]

我知道我可以只使用我的初始列表并从头开始删除每个迭代的项目。但是,是否有一些 native Python 函数可以用于此或更优雅的东西?

最佳答案

您可以使用 enumerate 生成元素及其在列表中的索引。

myList = [a,b,c,d,e,f,g]
for index, item in enumerate(myList):
try:
some_func(item)
except:
return myList[index:]

Test-it online

关于python - 如何在 Python 的 for 循环中检索剩余的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65577801/

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