简体   繁体   English

用于列表或子列表中的项目

[英]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语句现在的样子:

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? 什么是重写所以最有效的方法item是从来没有的子列表中的一个,所以该代码将再次在所有子表的运行每一个项目,除了列表中的每个项目?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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