控制嵌套列表/字符串上的递归 [英] Control recursion on nested lists / strings

查看:49
本文介绍了控制嵌套列表/字符串上的递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下输入内容:

Assume I have the following input:

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

,我想对items执行一些递归操作.

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

这将产生:

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

现在如何修改flatten(),以便产生以下内容(对于任意嵌套级别)?

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]

推荐答案

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

Just add a length check next to the shallow check:

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

这篇关于控制嵌套列表/字符串上的递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆