Morvern Morvern - 2 years ago 324
Python Question

loop and process items in list, reloop until all items have been processed

I've found similar but not identical questions 742371 and 4081217 with great answers, but haven't come to a solution to my problem.

I'm trying to process items in a list in place while it's being looped over, and re-loop over what's remaining in the list if it has not met a conditional. The conditional will eventually be met as True for all items in the list, but not necessarily on a "known" iteration. It reminds me of building a tree to some degree, as certain items in the list must be processed before others, but the others may be looped over beforehand.

My first instinct is to create a recursive function and edit a slice copy of the list. However I'm having little luck ~

I won't initially know how many passes it will take, but it can never be more passes than elements in the list... just by the nature of at least one element will always meet the conditional as True

Ideally ... the result would be something like the following

# initial list
myList = ['it1', 'test', 'blah', 10]
newList = []

# first pass
newList = ['test']

# 2nd pass
newList = ['test', 'blah', 10]

# 3rd pass
newList = ['test', 'blah', 10, 'it1']

Answer Source
current = ['it1', 'test', 'blah', 10]
results = []
while current:
    remaining = []
    for item in current:
        (results if meets_conditional(item) else remaining).append(item)
    current = remaining
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download