我想从嵌套列表中总结一个列表总数。
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']]]
列表总和为6
方法1
给我4个
print sum(1 for x in datalist if isinstance(x, list))
# 4
方法2
给我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
如何总结列表数量?
答案 0 :(得分:2)
您可以通过一些递归来执行此操作,因为您已经在某个函数中显示过
如果项目为count
且该项目不包含任何列表,则该函数仅向list
添加1。否则,递归地再次调用该项目。
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
答案 1 :(得分:2)
以下是工作流程:
>>> 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