1

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

3
  • You want to end up with the 4 lists or just the first or last one? Commented Jun 19, 2020 at 12:14
  • @kubatucka I want to end up with whole list of lists as shown in the last code block. Commented Jun 19, 2020 at 12:25
  • 1
    What have you tried so far? Commented Jun 19, 2020 at 12:54

2 Answers 2

1

flat flattens input array
walk recursively walks tree and unpacks values

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:])

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))])
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

I'm sorry it took long, thank you very much I'm really happy with this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.