简体   繁体   中英

Creating a tree diagram from list of lists

I have a 2D list:

#      #                #          ^      #    ^           #         ^
l = [['A', '1', '2'], ['B', 'xx', 'A'], ['C', 'B', 's'], ['D', 'd', 'B']]

and the first element in each list can be treated as an #ID string (in the example: A, B, C, D ). Anywhere where the ID's ( A, B, C, D ) occur in the second dimension's lists I would like to replace it with the content of the actual list. Example: ['B', 'xx', 'A'] should become ['B', 'xx', ['A', '1', '2']] because A is an #ID (first string of list) and it occurs in the second list. Output should be:

n = [['A', '1', '2'], ['B', 'xx', ['A', '1', '2']], ['C', ['B', 'xx', ['A', '1', '2']], 's'],
     ['D', 'd', ['B', 'xx', ['A', '1', '2']]]]

The problem I am facing is that there can be longer lists and more branches so it's getting complicated. In the end I am trying to build a tree diagram. I was thinking of calculting first what is the highest branching but don't have a solution in mind yet.

l = [['A', '1', '2'], ['B', 'xx', 'A'], ['C', 'B', 's'], ['D', 'd', 'B']]

dic  = {i[0]:i for i in l}

for i in l:
    fv = i[0]

    for j, v in enumerate(i):

        if v in dic and j!=0:
            dic[fv][j] = dic[v]

res = [v for i,v in dic.items()]
print(res)

output

[['A', '1', '2'],
 ['B', 'xx', ['A', '1', '2']],
 ['C', ['B', 'xx', ['A', '1', '2']], 's'],
 ['D', 'd', ['B', 'xx', ['A', '1', '2']]]]

Have you tried using a dictionary? If you have the ID's then you could possibly refer to them and then loop through the array and change entries. Below is what I had

l = [['A', '1', '2'], ['B', 'xx', 'A'], ['C', 'B', 's'], ['D', 'd', 'B'], ['E', 'C', 'b']]
dt = {}
for i in l:
    dt[i[0]] = i
for i in range(len(l)):
    for j in range(1, len(l[i])):
        if(l[i][j] in dt):
            l[i][j] = dt.get(l[i][j])
print(l)

Another more succinct version:

d = {item[0]: item for item in l}
for item in l:
    item[1:] = [d.get(element, element) for element in item[1:]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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