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(']['))
题
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!
解决方案
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(']['))
其他提示
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:
Here is what I have in mind:
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