Pergunta

So I have a giant list, that has a number of lists nested within it, and I want to get a count of the number of lists that are within this big outer list. The problem is that these lists aren't separated by anything, the look like this:

[[list1][list2][list3][list4]]

Please help!

Foi útil?

Solução

Based on the comments, it looks like your list looks something like

nested = ['[a][b][c][d]']

(So len(nested)=1, and type(nested_list[0]) is a str)

To count the number of "lists", you can do:

len(nested[0].split(']['))

Outras dicas

Supposing that your data is a string as it cannot possibly be a list, you can try the following iff the list is not nested more deeply and does not contain strings containing ][:

x = '[[list1][list2][list3][list4]]'
print (len (x.split ('][') ) )
>>> 4

Here are my assumptions, based on your description:

  • What you have is a string that looks almost like a list
  • Each item in this 'pseudo-list' is another 'pseudo-list'
  • The 'pseudo-list' might be nested to any level
  • You want to count these 'pseudo-list'

Here is what I have in mind:

  • I call the first list a level-1 list
  • We are interested to find out how many level-2 lists there are

Code:

import collections

li = '[[list1][list2][list3][list4]]'
counter = collections.Counter()
level = 0
for c in li:
    if c == '[':
        level += 1
        counter.update([level])
    elif c == ']':
        level -= 1

# We are interested in number of second-level lists
print 'List length:', counter[2]

Output:

List length: 4

This code works for arbitrarily nested lists, such as:

li = '[[1][2][3][4[a][b][c][d]]]'

use a recursive function to walk the nested list tree

  nested_list = [[['list 1'],['list 5']],['list2'],['list3'],['list4'],{'hello':'world'}]

 def countLists(nested_list):
   #print(nested_list)
   if len(nested_list)==1 & isinstance(nested_list,list):
        #print("return")
        return 1

    count=0
    for alist in nested_list:
         if isinstance(alist, list):
            retCount=countLists(alist)
            count+=retCount
            #print(alist)
    return count
        
countLists(nested_list)

output: 5

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top