Control recursion on nested lists / strings

旧街凉风 提交于 2020-02-04 02:27:12

问题


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]

回答1:


Just add a length check next to the shallow check:

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


来源:https://stackoverflow.com/questions/59903362/control-recursion-on-nested-lists-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!