简体   繁体   中英

for item in list or in sublist

I have a list which may or may not include further sublists. I need to run a block of code for every item in the list, and for every item in any sublists in the list. This is what my for statement looks like right now:

for item in mylist:
    ...

What is the most efficient way to rewrite that so item is never one of the sublists, and so that the code will run once for every item in all of the sublist, in addition to every item in the list?

There are two general ways to do this, either recursively:

def unroll_recursive(lst):
    for el in lst:
        if isinstance(el, list):
            yield from unroll_recursive(el)
        else:
            yield el

Or iteratively

from collections import deque
def unroll_iterative(lst)
    q = deque(lst)
    while q:
        el = q.popleft()
        if isinstance(el, list):
            q.extend(el)
        else:
            yield el

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM