我正在嘗試創建一個函式,它接受一個陣列并回傳按深度排序的陣列:
sortArrDepth([1, [5, 6], [4, 67, [34]], 7])
會回來
[[1, 7], [5, 6, 4, 67], [34]]
但是,它必須能夠處理任何最大深度的陣列,我寧愿不使用任何外部模塊。如果有幫助,這里有一個獲得最大深度的函式:
def getAstDepth(ast):
depth = 0
for i in last:
if isinstance(i, list):
depth = max(getAstDepth(i), depth)
return depth
任何幫助表示贊賞!
uj5u.com熱心網友回復:
這是使用遞回函式的一種方法:
def sortArrDepth(l, out=[], depth=0):
if len(out)<=depth:
out = [[] for _ in range(depth-len(out) 1)]
for v in l:
if isinstance(v, list):
sortArrDepth(v, out=out, depth=depth 1)
else:
out[depth].append(v)
return out
例子:
>>> sortArrDepth([1, [5, 6], [4, 67, [34]], 7])
[[1, 7], [5, 6, 4, 67], [34]]
>>> sortArrDepth([1, [5, 6], [[[0]]], [4, 67, [34]], 7])
[[1, 7], [5, 6, 4, 67], [34], [0]]
uj5u.com熱心網友回復:
您可以使用itertools.zip_longest和遞回來獲得更深的層次:
from itertools import zip_longest
def sort_by_depth(seq):
first = [item for item in seq if not isinstance(item, list)]
nested = [sort_by_depth(item) for item in seq if isinstance(item, list)]
return [first] [sum(item, start=[]) for item in zip_longest(*nested, fillvalue=[])]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/435728.html
