# 如何使用递归来计算嵌套列表的最大长度？

##### 问题描述投票：1回答：4

``````def max_length(obj):
"""
Return the maximum length of obj or any of its sublists, if obj is a list.
otherwise return 0.

@param object|list obj: object to return length of
@rtype: int

>>> max_length(17)
0
>>> max_length([1, 2, 3, 17])
4
>>> max_length([[1, 2, 3, 3], 4, [4, 5]])
4
"""
if isinstance(obj,int):
return 0
else:
return max([len(x) for x in obj])
``````

python list python-3.x recursion maxlength
##### 4个回答
1

1. `obj`只是一个`int`eger，你需要返回`0`
2. `obj``list`egers一个`int`你需要返回`len``list`gth
3. `obj`是异构`list`，你需要递归。

A码例如可以是

``````>>> def max_length(obj):
...     if isinstance(obj,int):
...         return 0
...     elif all(isinstance(i,int) for i in obj):
...             return len(obj)
...     else:
...         return max(max_length(i) for i in obj)
...
>>> max_length(17)
0
>>> max_length([1, 2, 3, 17])
4
>>> max_length([[1, 2, 3, 3], 4, [4, 5]])
4
``````

1

``````def nested_list(l):
if type(l) is not list:
return 0

lens = [len(l)]

for x in l:
lens.append(nested_list(x))
return max(lens)
``````

...如果你想成为更Python和鸭式吧...

``````def nested_list(l):
try:
lens = [len(l)]
except TypeError:
return 0

for x in l:
lens.append(nested_list(x))
return max(lens)
``````

0

```def max_length(obj): if isinstance(obj,int): return 0 else: return max(len(obj), max([max_length(i) for i in obj]))```

0

``````result = []
if isinstance(obj, int):
result.append(0)
else:
for sublist in obj:
result.append(max_length(sublist))
result.append(len(obj))
return max(result)
``````