简体   繁体   English

从嵌套字典值(树)创建列表列表

[英]Creating list of lists from nested dictionary values (tree)

I have used hierarchical clustering to create a tree of clusters.我使用层次聚类来创建一棵聚类树。

This results in:这导致:

dic = {6: {2: 2, 5: {3: 3, 4: {0: 0, 1: 1}}}}

lists in list according to clusters:根据集群列出列表:

[ [[6]],
  [[2], [5]],
  [[2], [3], [4]],
  [[2], [3], [0], [1]] ]

lists in list according to values:根据值列出列表:

[ [[2, 3, 0, 1]],
  [[2], [3, 0, 1]],
  [[2], [3], [0, 1]],
  [[2], [3], [0], [1]] ]

What I want to end up with is 'lists in list according to values'.我想要结束的是“根据值列出列表”。

Thanks谢谢

I just spent way too much time for this:我只是为此花了太多时间:

def list_of_list(d):
    if type(d)!=dict:
        return [[[d]]]
    results=[]
    for k,value in d.items():
        results.append(list_of_list(value))
    L=len(max(results,key=len))
    for i in range(len(results)):
        j=len(results[i]) 
        results[i].extend([results[i][j-1]]*(L-j))
    outputtop=[v  for result in results for v in result[0][0]]
    output=[[outputtop]]
    for l in range(L):
        output.append([ val  for result in results for  val in result[l]])
    return output

flat flattens input arrayflat输入数组
walk recursively walks tree and unpacks values walk递归地遍历树并解包值

final list comprehension that generates array same length as number of values extracted最终列表推导生成的数组长度与提取的值的数量相同
each array element is an array with x single value arrays from l ( l[i:i+1] ) concatenated with array slice of rest of elements in l ( l[x:] )每个数组元素是一个数组,其中 x 单个值 arrays 来自 l ( l[i:i+1] ),与 l ( l[x:] ) 中元素的 rest 的数组切片连接

dic = {6: {2: 2, 5: {3: 3, 4: {0: 0, 1: 1}}}}
flat = lambda l: [item for sublist in l for item in sublist]
walk = lambda node: flat([walk(v) if type(v) is dict else [v] for v in node.values()])

l = walk(dic)
print([[l[i:i+1] for i in range(x)]+[l[x:]] for x in range(len(l))])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM