How can I retrieve the remaining items in a for loop in Python?

梦想与她 提交于 2021-01-28 04:59:19

问题


I have a simple for loop iterating over a list of items. At some point, I know it will break. How can I then return the remaining items?

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]

I know I could just take my inital list and delete the the items from the beginning for every iteration one by one. But is there maybe some native Python function for this or something more elegant?


回答1:


You can make use of enumerate that yields both the element and its index in the list.

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




回答2:


You could use itertools.dropwhile, you use a test method to apply some_func, when it raises an error, the test becomes False and so it stops and dropwhile return the remaining ones

from itertools import dropwhile
    
def my_fct():
    def test(v):
        try:
            some_func(v)
            return False
        except:
            return True    
    return list(dropwhile(test, [a, b, c, d, e, f, g]))



回答3:


def test():
    myList = [1,2,3,4,0,7,8,9]
    for index, item in enumerate(myList):
        try: 
            print(index,item)
            1/item
        except:
            return(myList[index:]) 


来源:https://stackoverflow.com/questions/65577801/how-can-i-retrieve-the-remaining-items-in-a-for-loop-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!