简体   繁体   中英

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 .

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)?

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: 

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