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
添加回答
举报