假设我有以下输入:
items = [1, 2, [3, 4], (5, 6), 'ciao', range(3), (i for i in range(3, 6))]
我想对items
执行一些递归操作。
为了简单起见,假设我想要展平项目(但也可以是其他任何东西),一种方法是:
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()
以便我可以生成以下内容(对于任意嵌套级别)?
print(list(flatten(items, shallow=None)))
[1, 2, 3, 4, 5, 6, 'c', 'i', 'a', 'o', 0, 1, 2, 3, 4, 5]
<小时/>
支持的其他输入:
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
的方法,因为这非常脆弱,如果它出现另一种类型,该类型具有迭代它产生项目本身的属性。
最佳答案
如果你改变
if shallow and isinstance(item, shallow) or max_depth == 0:
至
if shallow and isinstance(item, shallow) or max_depth == 0 or item == items:
然后它就得到了所有三个例子。
关于python - 控制嵌套列表/字符串的递归(不检查类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59903905/