我有一个列表赋值给变量my_list
。其值为[[1,2,3],[3,5,[2,3]], [[3,2],[5,[4]]]]
。我需要找到my_list
的长度,但是len(my_list)
只返回3。我希望它返回11。是否有任何Python函数可以返回my_list
嵌套列表的完整长度。
示例:
Input
[[1,2,3],[3,5,[2,3]], [[3,2],[5,[4]]]]
Output
11
我希望这个功能不仅可以适用于数字,也可以适用于字符串。
我有一个列表赋值给变量my_list
。其值为[[1,2,3],[3,5,[2,3]], [[3,2],[5,[4]]]]
。我需要找到my_list
的长度,但是len(my_list)
只返回3。我希望它返回11。是否有任何Python函数可以返回my_list
嵌套列表的完整长度。
示例:
Input
[[1,2,3],[3,5,[2,3]], [[3,2],[5,[4]]]]
Output
11
我希望这个功能不仅可以适用于数字,也可以适用于字符串。
该函数计算列表的长度,将除列表以外的任何对象视为长度1,并在列表项上进行递归以查找平坦长度,在解释器最大堆栈深度范围内可处理任意嵌套程度。
def recursive_len(item):
if type(item) == list:
return sum(recursive_len(subitem) for subitem in item)
else:
return 1
注意:根据使用情况,最好检查该项是否可迭代,而不是检查它是否具有类型list
,以正确判断元组的大小等。但是,检查对象是否可迭代会导致在字符串中计算每个字符而不是给出字符串长度1的副作用,这可能是不希望看到的。
if type(item) == list or type(item) == tuple or type(item)==dict
等等。 - user4414248item
是可迭代对象且不是字符串类型,则返回True。 - Padraic Cunninghamif isinstance(item, (list,tuple))
。 - Padraic Cunningham作为替代方案,您可以使用flatten和len:
from compiler.ast import flatten
my_list = [[1,2,3],[3,5,[2,3]], [[3,2],[5,[4]]]]
len(flatten(my_list))
11
PS. 感谢 @thefourtheye 的指出,请注意:
自2.6版本起已弃用:编译器包在Python 3中已被删除。
可以在此处找到替代方案:Python 3替代已弃用的编译器.ast平坦函数
compiler.ast.flatten
已经很久以前就被弃用了。 - thefourtheye这是一个 hack 方法,可能有人已经发布过了。将列表转换为字符串(让 __str__
操作完成重活和递归),然后计算逗号的数量并加1。
>>> my_list = [[1,2,3],[3,5,[2,3]], [[3,2],[5,[4]]]]
>>> str(my_list).count(",")+1
11
(适用于整数和浮点数,但对字符串无效,因为它们可以包含逗号)
编辑:这种方法不能处理空列表:我们必须删除[]
元素:
>>> my_list = [[1,2,3],[3,5,[2,3]], [[3,2],[5,[4],[]]]] # added empty list at the end
>>> s = str(my_list)
>>> s.count(",")-s.count("[]")+1 # still 11
,
时,对于字符串列表无效。 - Harshal Parekh这是一种备选方案,可能不太高效,因为它填充一个新的扁平列表,并在最后返回:
def flatten_list(ls, flattened_list=[]):
for elem in ls:
if not isinstance(elem, list):
flattened_list.append(elem)
else:
flatten_list(elem, flattened_list)
return flattened_list
flatten_list
直观地将列表展开,然后您可以使用 len()
函数计算新返回的展平列表的长度:
len(flatten_list(my_list))
def is_leaf(tree):
return type(tree) != list
def count_leaves(tree):
if is_leaf(tree):
return 1
else:
branch_counts = [count_leaves(b) for b in tree]
return sum(branch_counts)
count_leaves函数通过递归计算分支的branch_counts,然后将这些结果相加来计算树中的叶子数。基本情况是当树是一个叶子时,即只有1个叶子的树。叶子的数量与树的长度不同,树的长度是其分支数。
def nestedList(check):
returnValue = 0
for i in xrange(0, len(check)):
if(isinstance(check[i], list)):
returnValue += nestedList(check[i])
else:
returnValue += 1
return returnValue
这是我最好的尝试,利用递归,仅使用标准库和视觉。 我尽量不使用自定义库。
def listlength(mylist, k=0, indent=''):
for l1 in mylist:
if isinstance(l1, list):
k = listlength(l1, k, indent+' ')
else:
print(indent+str(l1))
k+=1
return k
a = [[1,2,3],[3,5,[2,3]], [[3,2],[5,[4]]]]
listlength(a)
# 11
而且为了保险起见
a = []
x = listlength(a)
print('length={}'.format(x))
# length=0
a = [1,2,3]
x = listlength(a)
print('length={}'.format(x))
#1
#2
#3
#length=3
a = [[1,2,3]]
x = listlength(a)
print('length={}'.format(x))
# 1
# 2
# 3
#length=3
a = [[1,2,3],[1,2,3]]
x = listlength(a)
print('length={}'.format(x))
# 1
# 2
# 3
# 1
# 2
# 3
#length=6
a = [1,2,3, [1,2,3],[1,2,3]]
x = listlength(a)
print('length={}'.format(x))
#1
#2
#3
# 1
# 2
# 3
# 1
# 2
# 3
#length=9
a = [1,2,3, [1,2,3,[1,2,3]]]
x = listlength(a)
print('length={}'.format(x))
#1
#2
#3
# 1
# 2
# 3
# 1
# 2
# 3
#length=9
a = [ [1,2,3], [1,[1,2],3] ]
x = listlength(a)
print('length={}'.format(x))
# 1
# 2
# 3
# 1
# 1
# 2
# 3
#length=7
len()
即可。 - PM 2Ringlen()
。例如,len(list(flatten(deep_nested_list)))
。 - PM 2Ring