Вот код, который должен делать то, что вы хотите.
Я включил две версии функции, одну для ясности, а другую, которая меньше, но функционально идентична.
####################
# 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