简体   繁体   English

控制嵌套列表/字符串的递归

[英]Control recursion on nested lists / strings

Assume I have the following input:假设我有以下输入:

items = [1, 2, [3, 4], (5, 6), 'ciao', range(3), (i for i in range(3, 6))]

and I want to perform some recursive operation on items .我想对items执行一些递归操作。

For the sake of simplicity, let's say I want to flatten items (but could be anything else), one way of doing this would be:为了简单起见,假设我想展平项目(但可以是其他任何东西),这样做的一种方法是:

def flatten(items, shallow=(str, bytes, bytearray)):
    for item in items:
        if isinstance(item, shallow):
            yield item
        else:
            try:
                yield from flatten(item)
            except TypeError:
                yield item

this would produce:这将产生:

print(list(flatten(items)))
[1, 2, 3, 4, 5, 6, 'ciao', 0, 1, 2, 3, 4, 5]

Now how could I modify flatten() so that I could produce the following (for arbitrary nesting levels)?现在我如何修改flatten()以便我可以生成以下内容(对于任意嵌套级别)?

print(list(flatten(items)))
[1, 2, 3, 4, 5, 6, 'c', 'i', 'a', 'o', 0, 1, 2, 3, 4, 5]

只需在浅检查旁边添加一个长度检查:

if isinstance(item, shallow) and len(item) == 1: 

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

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