为什么 len([1,[2,[3]]]]) return 2,而 len([1,[2]]) 也 return 2?

Why does len([1,[2,[3]]]]) return 2, while len([1,[2]]) also return 2?

我正在尝试编写一个函数 def list_average(list_input),它接受一个列表,例如 [1, 2, 3][1,[2,[3]]]] 和 returns 中整数的平均值列表;但是,当我使用 len([1,[2,[3]]]]) 查找列表中的整数个数时,它 returns 2. 谁能解释一下?

我的代码如下:

def list_average(list_input):
    n = sumaverage(list_input)
    count = len(list_input)
    if count == 0:
        return 0
    average = n / count
    return int(average)

len returns 仅顶层序列的长度。如果该序列中的元素恰好是序列,则不予考虑。

>>> len([1,2,3])              # list of 3 ints
3
>>> len([[1,2],[3,4],[5,6]])  # list of 3 sub-lists
3
>>> len([1, [2,3], [[4,5,6], [7,8,9]]])  # list of mixed types, some are themselves lists
3

如果你在寻找“我的列表中有多少 non-list 个元素”之类的东西,你可以做一些递归的事情,比如

def recursive_len(data):
    if isinstance(data, list):
        return sum(recursive_len(i) for i in data)
    else:
        return 1

>>> recursive_len([1,2,3])
3
>>> recursive_len([[1,2],[3,4],[5,6]])
6
>>> recursive_len([1, [2,3], [[4,5,6], [7,8,9]]])
9

len([1,[2,[3]]]]) 有一个包含两个元素的列表作为输入:列表的第一个元素是整数 1,第二个元素是列表 [2,[3]].