[英]How to Sum up number of 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']]]
清單的總和是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
如何匯總列表數量?
您可以通過一些遞歸來做到這一點,正如您已經在其中一個函數中所示的那樣
如果該項目是list
並且該項目不包含任何list
,則該函數僅加1進行count
。 否則,將在該項目上再次遞歸調用該函數。
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
這是工作流程:
>>> 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.