3 回答

TA貢獻1829條經驗 獲得超7個贊
這可能會將您推向正確的方向:
def lenall(lst):
if isinstance(lst, list):
return 1 + sum(map(lenall, lst))
return 0
>>> lenall(listlist)
12
這實際上計算了數據結構中列表的總數。如果要添加所有長度,則必須將其更改為:
def lenall(lst):
if isinstance(lst, list):
return len(lst) + sum(map(lenall, lst))
return 0
>>> lenall(listlist)
11

TA貢獻1789條經驗 獲得超8個贊
這是一個可能的解決方案:
listlist = [[], [[[[], []], [[]], []]], [[]]]
def length(lst):
return len(lst) + sum(length(l) for l in lst if isinstance(l, list))
print(length(listlist))
輸出
11

TA貢獻1828條經驗 獲得超3個贊
這是應該做你想做的事情的代碼。
我包含了該函數的兩個版本,一個是為了清楚起見,另一個是更小但功能相同。
####################
# Create a list of lists / elements
####################
#x = [[1,2,3],[3,4],[3,4,[3,4,5],[4],[5,4,6]],[4,3,4,5,[[[6]]]]]
x = [[], [[[[], []], [[]], []]], [[]]]
############################################################
# First implementation (included for clarity)
############################################################
def get_len_lists(this_list):
# Set number of elements to 0
num_elem = 0
# Loop through each element in the list...
for elem in this_list:
# .. if it's a list...
if type(elem) == list:
# ... if the list is empty, count that as an element
if elem == list():
# ... so add one
num_elem += 1
else:
# ... get the number of elements...
num_elem += get_len_lists(elem) + 1
# ... otherwise...
else:
# ... just add one to the length of the list
num_elem += 1
# Return the number of elements in the list
return num_elem
############################################################
# Smaller implementation
############################################################
def get_len_lists_2(this_list):
# Set number of elements to 0
num_elem = 0
# Loop through each element in the list...
for elem in this_list:
# We add one for each level, regardless of whether it is an element or a list
num_elem += 1
# If it's a list...
if type(elem) == list:
# .. get the number of elements in the list
num_elem += get_len_lists(elem)
# Return the number of elements in the list
return num_elem
result1 = get_len_lists(x) + 1
result2 = get_len_lists_2(x) + 1
print(result1)
print(result2)
輸出是:
12
12
添加回答
舉報