Reputation: 3282
I want to sum up a total number of list from a nested list.
datalist = [['a', 'b', 'c', 'a'], [['b', 'd', 'a', 'c'], ['a', 'a', 'a', 'b']], ['a', 'b', 'g', 'h'], [['x', 'z', 'c', 'c'], ['b', 'c', 'b', 'a']]]
Sum of list is 6
Approach 1
Gives me 4
print sum(1 for x in datalist if isinstance(x, list))
# 4
Approach 2
Gives me 8
def count_list(l):
count = 0
for e in l:
if isinstance(e, list):
count = count + 1 + count_list(e)
return count
print count_list(datalist)
#8
How can I sum up the number of list?
Upvotes: 1
Views: 265
Reputation: 78554
You may be able to do this with some recursion, as you've already shown in one of your functions
The function only adds 1 to count
if the item is a list
and the item does not contain any lists. Else, the function is called on the item again, recursively.
datalist = [['a', 'b', 'c', 'a'], [['b', 'd', 'a', 'c'], ['a', 'a', 'a', 'b']], ['a', 'b', 'g', 'h'], [['x', 'z', 'c', 'c'], ['b', 'c', 'b', 'a']]]
def count_nested_lists(lst):
count = 0
for item in lst:
if isinstance(item, list):
if not any(isinstance(l, list) for l in item):
count += 1
else:
count += count_nested_lists(item)
return count
print(count_nested_lists(datalist))
# 6
Upvotes: 2
Reputation: 16043
Here is the working flow :
>>> def count(local_list):
... sum1 = 0
... for l in local_list:
... if not isinstance(l,list):
... return 1
... else:
... sum1+= count(l)
...
... return sum1
...
>>> count([['a', 'b', 'c', 'a'], [['b', 'd', 'a', 'c'], ['a', 'a', 'a', 'b']], ['a', 'b', 'g', 'h'], [['x', 'z', 'c', 'c'], ['b', 'c', 'b', 'a']]])
6
Upvotes: 2