小编Oli*_*ver的帖子

如何在列表中查找嵌套列表的数量?

该函数接受一个列表并返回一个int,具体取决于列表中有多少列表不包括列表本身.(为简单起见,我们可以假设所有内容都是整数或列表.)

例如:

x=[1,2,[[[]]],[[]],3,4,[1,2,3,4,[[]] ] ]

count_list(x) # would return 8
Run Code Online (Sandbox Code Playgroud)

我认为使用递归会有所帮助,但我不知道如何实现它,这是我到目前为止所做的.

def count_list(a,count=None, i=None):

    if count==None and i==None:
        count=0
        i=0
    if i>len(a)
        return(count)
    if a[i]==list
       i+=1
       count+=1
       return(count_list(a[i][i],count))
    else:
        i+=1
        return(count_list(a[i]))
Run Code Online (Sandbox Code Playgroud)

python recursion list python-3.x

16
推荐指数
3
解决办法
5003
查看次数

如何在输入中找到列表的数量?(蟒蛇)

def lists(A: list) -> int:

    '''Return the total number of lists in A (including A itself).
    Each element of A and any  nested lists are either ints or other lists.

    Example:
    >>> lists([1, 2, 3])
    1
    >>> lists([[1], [2], [3]])
    4
    >>> lists([[[1, 2], [], 3]])
    4
    '''
Run Code Online (Sandbox Code Playgroud)

有谁知道如何做到这一点?我只有

for i in range(0, len(A)):
    if (isinstance(A[i], list)):
        count=count+1
        return(lists(A[i]))
    else:
        B=A[i:]
return(count)
Run Code Online (Sandbox Code Playgroud)

python arrays recursion list

1
推荐指数
1
解决办法
86
查看次数

标签 统计

list ×2

python ×2

recursion ×2

arrays ×1

python-3.x ×1