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

时间:2014-07-05 00:54:14

标签: python arrays list recursion

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)

5 个答案:

答案 0 :(得分:5)

这是一个“肮脏的”'但很容易做到这一点

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

不需要递归

答案 1 :(得分:1)

以下是编写它的一种方法:

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

答案 2 :(得分:1)

你应该通过递归来做到这一点:

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

答案 3 :(得分:1)

def lists(A):
    return 1 + sum(lists(e) if isinstance(e, list) else 0 for e in A)

答案 4 :(得分:1)

def lists(a):

    if not isinstance(a, list):
        return 0

    s = 1

    for x in a:
        s += lists(x)

    return s

print lists([])
print lists([1,2,3])
print lists([[1], [2], [3]])
print lists([[[1, 2], [], 3]])