简体   繁体   English

如何查找列表中嵌套列表的数量?

[英]How to find the number of nested lists in a list?

The function takes a list and returns an int depending on how many lists are in the list not including the list itself.该函数接受一个列表并返回一个 int,具体取决于列表中有多少个列表,不包括列表本身。 (For the sake of simplicity we can assume everything is either an integer or a list.) (为了简单起见,我们可以假设一切都是整数或列表。)

For example:例如:

x=[1,2,[[[]]],[[]],3,4,[1,2,3,4,[[]] ] ]

count_list(x) # would return 8

I think using recursion would help but I am not sure how to implement it, this is what I have so far.我认为使用递归会有所帮助,但我不确定如何实现它,这就是我到目前为止所拥有的。

def count_list(a,count=None, i=None):

    if count==None and i==None:
        count=0
        i=0
    if i>len(a)
        return(count)
    if a[i]==list
       i+=1
       count+=1
       return(count_list(a[i][i],count))
    else:
        i+=1
        return(count_list(a[i]))

You can use a recursive function as following:您可以使用递归函数,如下所示:

In [14]: def count_lists(l):
    ...:     return sum(1 + count_lists(i) for i in l if isinstance(i,list))
    ...: 

In [15]: 

In [15]: x=[1,2,[[[]]],[[]],3,4,[1,2,3,4,[[]] ] ]

In [16]: count_lists(x)
Out[16]: 8

This seems to do the job:这似乎可以完成这项工作:

def count_list(l):
    count = 0
    for e in l:
        if isinstance(e, list):
            count = count + 1 + count_list(e)
    return count

Here is a non-recursive solution:这是一个非递归的解决方案:

  1. First, put every items of the list into a stack首先,将列表中的每一项放入堆栈
  2. Keep popping an item off the stack until it is exhausted继续从堆栈中弹出一个项目,直到它用完
  3. If the item is a list: a) count it, b) push every items in in to the stack如果该项目是一个列表:a)计算它,b)将每个项目推入堆栈

The code:编码:

def count_list(lst):
    """ Given a master list, count the number of sub-lists """
    stack = lst[:]
    count = 0
    while stack:
        item = stack.pop()
        if isinstance(item, list):
            # If the item is a list, count it, and push back into the
            # stack so we can process it later
            count += 1
            stack.extend(item)
    return count

A functional-style solution without loops.没有循环的函数式解决方案。 Recursively processes the first element of a list, and the tail of a list.递归处理列表的第一个元素和列表的尾部。 Add one for each empty-list encountered (that is, once we finish processing some list, its tail becomes empty, and we add 1 to the result).为遇到的每个空列表添加一个(也就是说,一旦我们处理完某个列表,它的尾部就变为空,我们将结果加 1)。 And subtract 1 for the list itself.并为列表本身减去 1。

def number_of_lists(x):
    f = lambda x: 0 if not isinstance(x,list) else (f(x[0]) + f(x[1:]) if len(x) else 1)
    return f(x) - 1

Results:结果:

x=[1,2,[[[]]],[[]],3,4,[1,2,3,4,[[]] ] ]
number_of_lists(x)
>> 8

I like this tail recursive solution, although it's not much use in Python...我喜欢这个尾递归解决方案,虽然它在 Python 中用处不大……

def count_lists(l, counter):
    if (len(l) == 0):
        return counter
    else:
        e = l.pop(0)
        if (isinstance(e, list)):
            l.extend(e)
            return count_lists(l, 1 + counter)
        else:
            return count_lists(l, counter)

x=[1,2,[[[]]],[[]],3,4,[1,2,3,4,[[]]]]
print(count_lists(x, 0))
lst = [1,2,[[[]]],[[]],3,4,[1,2,3,4,["[[[[[][[[[[[[[[[[[["] ] ]

strlst = re.sub("'.*?'", '',str(lst))
print(strlst.count("[")-1)

Making the list a string will allow you to use count function on the number of [ or ] giving you an answer将列表设为字符串将允许您对[]的数量使用 count 函数给您答案

But if a string within the list contains either [ or ] they will be included so removing all strings within the list using regex eliminates this problem但是,如果列表中的字符串包含[]它们将被包括在内,因此使用正则表达式删除列表中的所有字符串可以消除此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM