简体   繁体   中英

Modify a tuple list to one showing its hierarchy

I have a list of tuples as below:

my_lists = [("a",["c","d","e"]),("c",["f","g"]),("d",["h"]),("h",["w","n"]),("n",["k"])]

This list has the levels shown by the first element of each tuple, and they should be merged into a tuple list representing its hierarchy like this:

result = [("a", [ ("c", ["f","g"]), ("d", [("h", ["w", ("n", ["k"] )] )] ) ,"e"])]

Is there any way to do it?

If possible, it would be great to find a way to return the depth level of a given letter.

"a" depth level: 5 (the highest)
"d" depth level: 2
"k" depth level: 0 (the lowest)

Try this:

my_lists = [("a",["c","d","e"]),("c",["f","g"]),("d",["h"]),("h",["w","n"]),("n",["k"])]

abc = {}
for key, value in my_lists[::-1]:
    new_value = []
    for v in value:
        new_value.append(abc.get(v, v))
    abc[key] = (key, new_value)
result = [abc[my_lists[0][0]]]

print(result)

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