能否快速获取python中一个列表中最内层子列表的最小长度?
Can I quickly get the minimum length of the most inner sub-lists within a list in python?
This展示如何获取一级内表的最小长度
我怎样才能 return 4
这个列表
b=[[1,0,1,2,1,1,1,3111111,[1,1,6,7]],[31,1,4,51,1,1,1],[1,1,6,7,8]]
因为 [1,1,6,7]
只有 4 个元素。
我可以 运行 一个 for 循环来得到它。但是可以更简单吗?
我的意思是"the length of the shortest list that is at the same depth as the deepest list"。
v1,任意深度的最小长度:
>>> b = [[1,0,1,2,1,1,1,3111111,[1,1,6,7]],[31,1,4,51,1,1,1],[1,1,6,7,8]]
>>> def lists_in(L):
... for element in L:
... if isinstance(element, list):
... yield element
... yield from lists_in(element)
...
>>> min(lists_in(b), key=len)
[1, 1, 6, 7]
>>> len(min(lists_in(b), key=len))
4
v2,新要求 "the length of the shortest list that is at the same depth as the deepest list":
>>> def depths_and_lengths(L, depth=0):
... for element in L:
... if isinstance(element, list):
... yield (depth, len(element))
... yield from depths_and_lengths(element, depth-1)
...
...
>>> min(depths_and_lengths(b))[1]
4
>>> min(depths_and_lengths([[[1, 2]]]))[1] # Stefan Pochmann example
2
这是一个错误的答案:
def mpr(x, inital=[]):
if isinstance(x, list):
inital.append(len(x))
map(lambda x: mpr(x, inital), x)
return inital
mpr(b)
-> [3, 9, 4, 7, 5]
This展示如何获取一级内表的最小长度
我怎样才能 return 4
这个列表
b=[[1,0,1,2,1,1,1,3111111,[1,1,6,7]],[31,1,4,51,1,1,1],[1,1,6,7,8]]
因为 [1,1,6,7]
只有 4 个元素。
我可以 运行 一个 for 循环来得到它。但是可以更简单吗?
我的意思是"the length of the shortest list that is at the same depth as the deepest list"。
v1,任意深度的最小长度:
>>> b = [[1,0,1,2,1,1,1,3111111,[1,1,6,7]],[31,1,4,51,1,1,1],[1,1,6,7,8]]
>>> def lists_in(L):
... for element in L:
... if isinstance(element, list):
... yield element
... yield from lists_in(element)
...
>>> min(lists_in(b), key=len)
[1, 1, 6, 7]
>>> len(min(lists_in(b), key=len))
4
v2,新要求 "the length of the shortest list that is at the same depth as the deepest list":
>>> def depths_and_lengths(L, depth=0):
... for element in L:
... if isinstance(element, list):
... yield (depth, len(element))
... yield from depths_and_lengths(element, depth-1)
...
...
>>> min(depths_and_lengths(b))[1]
4
>>> min(depths_and_lengths([[[1, 2]]]))[1] # Stefan Pochmann example
2
这是一个错误的答案:
def mpr(x, inital=[]):
if isinstance(x, list):
inital.append(len(x))
map(lambda x: mpr(x, inital), x)
return inital
mpr(b)
-> [3, 9, 4, 7, 5]