控制嵌套列表/字符串上的递归(不检查类型) [英] Control recursion on nested lists / strings (without checking for the type)
问题描述
假设我有以下输入内容:
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, max_depth=-1, shallow=(str, bytes, bytearray)):
for item in items:
if shallow and isinstance(item, shallow) or max_depth == 0:
yield item
else:
try:
for subitem in flatten(item, max_depth - 1, shallow):
yield subitem
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, shallow=None)))
[1, 2, 3, 4, 5, 6, 'c', 'i', 'a', 'o', 0, 1, 2, 3, 4, 5]
要支持的其他输入:
Other inputs to be supported:
items = [['best', 'func'], 'ever']
print(list(flatten(items, shallow=None)))
# ['b', 'e', 's', 't', 'f', 'u', 'n', 'c', 'e', 'v', 'e', 'r']
注意:我正在寻找一种不依赖显式检查str
,bytes
或bytearray
的方法,因为它很脆弱,如果它出现具有迭代功能的另一种类型,则该类型会产生项目本身.
Note: I am looking for an approach that does not rely on explicitly checking for str
, bytes
or bytearray
as this is quite brittle, should it appear another type which has the property that iterating through it yields the item itself.
这与以下内容有关:对嵌套列表/字符串的控制递归
推荐答案
如果您更改
if shallow and isinstance(item, shallow) or max_depth == 0:
到
if shallow and isinstance(item, shallow) or max_depth == 0 or item == items:
然后正确地处理了所有三个示例.
then it gets all three examples right.
这篇关于控制嵌套列表/字符串上的递归(不检查类型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!