简体   繁体   English

Python 检查列表是否嵌套

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

I have a list, sometimes it is nested, sometimes it is not.我有一个列表,有时是嵌套的,有时不是。 Based whether it is nested, the continuation is different.根据是否嵌套,延续不同。 How do I check if this list is nested?如何检查此列表是否嵌套? True or False should be output.应该输出TrueFalse

example:例子:

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

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

You can use isinstance and a generator expression combined with any . 您可以使用isinstance生成器表达式结合any This will check for instances of a list object within your original, outer list. 这将检查原始外部列表中的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

Note that any will return True as soon as it reaches an element that is valid (in this case if the element is a list) so you don't end up iterating over the whole outer list unnecessarily. 请注意, any一旦到达有效的元素(在这种情况下,如果元素是列表),它将返回True ,因此您不会不必要地迭代整个外部列表。

We want to check if elements inside outer-list is an instance of list or not, like @Ffisegydd said we can use a generator expression to build a generator and iterate over it using next() , If any element inside the outer-loop is an instance of list then calling next() on the generator will work otherwise if none of the element inside outer-loops belongs to an instance of list then calling next will raiseStopIteration我们想检查outer-list中的元素是否是list的一个实例,就像@Ffisegydd所说的,我们可以使用生成器表达式来构建一个生成器并使用next()对其进行迭代,如果外部循环中的任何元素是一个列表的实例然后在生成器上调用 next() 将起作用,否则如果外部循环内的元素都不属于列表的一个实例,则调用 next 将引发StopIteration

Best case : If it's a nested loop (we can stop iterating as soon as we see the first instance of list)最好的情况:如果它是一个嵌套循环(我们可以在看到列表的第一个实例后立即停止迭代)

Worst case : If it's not a nested loop (We need to iterate over all the elements inside the outerlist)最坏的情况:如果它不是嵌套循环(我们需要遍历外部列表中的所有元素)

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

Output :输出

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