如何找到输入中的列表数?(Python)

2024-04-27 09:04:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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
    '''

有人知道怎么做吗? 我所拥有的只是

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)

Tags: oftheinnumberreturndefcountlists
3条回答

您应该使用递归执行此操作:

def count_list(a):
    result = 0
    if isinstance(a, list):
        result += 1
    try:
        for b in a:
            result += count_list(b)
    except:
        pass
    return result

这里有一个'肮脏'但很容易做到这一点

def lists(l):
    '''
    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.
    '''

    # convert the list to string and count the ['s
    # each [ is the start of a list, so the number of ['s equals
    # the number of lists
    nr_of_lists = str(l).count('[')

    # return the number of sublists
    return nr_of_lists

不需要递归

有一种方法可以写:

def numlists(lst, num = 1):
    for item in lst:
        if isinstance(item, list):
            num += numlists(item)
    return num

示例输出:

print(numlists([1, 2, 3])) # 1
print(numlists([[1], [2], [3]])) # 4
print(numlists([[[1, 2], [], 3]])) # 4
print(numlists([[1,[2,3,[4,5,[6]]]],7,8,[9]])) # 6

相关问题 更多 >