簡體   English   中英

如何查找輸入中的列表數? (蟒蛇)

[英]How to find the number of lists in an input? (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)

這是一個“骯臟”但簡單的方法

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

您應該使用遞歸操作:

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(A):
    return 1 + sum(lists(e) if isinstance(e, list) else 0 for e in A)
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]])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM