gpt4 book ai didi

python - 控制嵌套列表/字符串的递归

转载 作者:行者123 更新时间:2023-12-03 07:41:46 25 4
gpt4 key购买 nike

假设我有以下输入:

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

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

为了简单起见,假设我想要展平项目(但也可以是其他任何东西),一种方法是:

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() 以便我可以生成以下内容(对于任意嵌套级别)?

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: 

关于python - 控制嵌套列表/字符串的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59903362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com