簡體   English   中英

Python 檢查列表是否嵌套

[英]Python check if a list is nested or not

我有一個列表,有時是嵌套的,有時不是。 根據是否嵌套,延續不同。 如何檢查此列表是否嵌套? 應該輸出TrueFalse

例子:

[1,2,3] --> False

[[1],[2],[3]] --> True

您可以使用isinstance生成器表達式結合any 這將檢查原始外部列表中的list對象的實例。

In [11]: a = [1, 2, 3]

In [12]: b = [[1], [2], [3]]

In [13]: any(isinstance(i, list) for i in a)
Out[13]: False

In [14]: any(isinstance(i, list) for i in b)
Out[14]: True

請注意, any一旦到達有效的元素(在這種情況下,如果元素是列表),它將返回True ,因此您不會不必要地迭代整個外部列表。

我們想檢查outer-list中的元素是否是list的一個實例,就像@Ffisegydd所說的,我們可以使用生成器表達式來構建一個生成器並使用next()對其進行迭代,如果外部循環中的任何元素是一個列表的實例然后在生成器上調用 next() 將起作用,否則如果外部循環內的元素都不屬於列表的一個實例,則調用 next 將引發StopIteration

最好的情況:如果它是一個嵌套循環(我們可以在看到列表的第一個實例后立即停止迭代)

最壞的情況:如果它不是嵌套循環(我們需要遍歷外部列表中的所有元素)

def is_nested_list(l):
    
    try:
          next(x for x in l if isinstance(x,list))
    
    except StopIteration:
        return False
    
    return True

def get_dict_values(data_structure):
    ''' Get a list with the values of a dictionary items '''

    [*values] = data_structure.values()

    return values

def get_list_values(data_structure, temp):
    ''' Transform a nested list into a one depth level list '''

    for item in data_structure:
        if type(item) == list:
            temp = ReturnDataValues.get_list_values(item, temp)

        elif type(item) == dict:
            dict_values = ReturnDataValues.get_dict_values(item)
            temp = ReturnDataValues.get_list_values(dict_values, temp)

        else:
            temp.append(item)

    return temp

def get_object_values(data_structure, result):
    ''' Get all the values of the elements of an object at all its depth levels '''

    data_type = type(data_structure)

    if data_type == dict:
        values = ReturnDataValues.get_dict_values(data_structure)
        ReturnDataValues.get_object_values(values, result)

    if data_type == list:
        ReturnDataValues.get_list_values(data_structure, result)

    return result


**nested_list** = ['a', 'b', ['c', 'd'], 'e', ['g', 'h', ['i', 'j', ['k', 'l']]] ]
print(get_list_values(nested_list))

輸出

 ['a', 'b', 'c', 'd', 'e', 'g', 'h', 'i', 'j', 'k', 'l']

暫無
暫無

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

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