gpt4 book ai didi

python - 如果深度达到 0,则递归查找嵌套列表的数量和元素值

转载 作者:行者123 更新时间:2023-12-03 22:59:13 24 4
gpt4 key购买 nike

我有一个嵌套列表,如果深度达到 0,我想返回嵌套列表的数量(或深度)和元素值。 .例如,对于下面的嵌套列表,我要返回的值是 (13, 37) .但我的代码返回 36只要。

nested = [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[13]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]

def search(a, depth=0):
count = 0
for e in a:
if isinstance(e, list):
count = count + 1 + search(e)
return count

search(nested)
应该如何更正我的代码以使其按预期返回 (13, 37)?

最佳答案

这给出了包含在一组列表中的单个值的正确答案。不知道为什么要遍历列表的元素。是否有潜在的多个嵌套子列表/值?

nested = [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[13]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
def search(a, depth=0):
if type(a) is list:
return search(a[0], depth + 1)
else:
return a, depth

print(search(nested))

关于python - 如果深度达到 0,则递归查找嵌套列表的数量和元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67249193/

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