|
1 | 1 | from collections import OrderedDict |
2 | | -from typing import Type |
| 2 | +from typing import List, Tuple, Type |
3 | 3 |
|
4 | 4 | import pandas as pd |
5 | 5 |
|
|
14 | 14 | "add_dict_to_tree_by_name", |
15 | 15 | "add_dataframe_to_tree_by_path", |
16 | 16 | "add_dataframe_to_tree_by_name", |
| 17 | + "list_to_tree_tuples", |
17 | 18 | "list_to_tree", |
18 | 19 | "dict_to_tree", |
19 | 20 | "nested_dict_to_tree", |
@@ -402,6 +403,49 @@ def add_dataframe_to_tree_by_name( |
402 | 403 | ) |
403 | 404 |
|
404 | 405 |
|
| 406 | +def list_to_tree_tuples( |
| 407 | + relations: List[Tuple[str, str]], |
| 408 | + node_type: Type[Node] = Node, |
| 409 | +) -> Node: |
| 410 | + """Construct tree from list of tuple containing parent-child names. |
| 411 | +
|
| 412 | + >>> from bigtree import list_to_tree_tuples, print_tree |
| 413 | + >>> relations_list = [("a", "b"), ("a", "c"), ("b", "d"), ("b", "e"), ("c", "f"), ("e", "g"), ("e", "h")] |
| 414 | + >>> root = list_to_tree_tuples(relations_list) |
| 415 | + >>> print_tree(root) |
| 416 | + a |
| 417 | + |-- b |
| 418 | + | |-- d |
| 419 | + | `-- e |
| 420 | + | |-- g |
| 421 | + | `-- h |
| 422 | + `-- c |
| 423 | + `-- f |
| 424 | +
|
| 425 | + Args: |
| 426 | + relations (list): list containing tuple containing parent-child names |
| 427 | + node_type (Type[Node]): node type of tree to be created, defaults to Node |
| 428 | +
|
| 429 | + Returns: |
| 430 | + (Node) |
| 431 | + """ |
| 432 | + if not len(relations): |
| 433 | + raise ValueError("Path list does not contain any data, check `relations`") |
| 434 | + |
| 435 | + node_dict = {} |
| 436 | + for parent_name, child_name in relations: |
| 437 | + if not node_dict.get(parent_name): |
| 438 | + node_dict[parent_name] = node_type(parent_name) |
| 439 | + if not node_dict.get(child_name): |
| 440 | + node_dict[child_name] = node_type(child_name) |
| 441 | + |
| 442 | + parent_node = node_dict[parent_name] |
| 443 | + child_node = node_dict[child_name] |
| 444 | + child_node.parent = parent_node |
| 445 | + root = child_node.root |
| 446 | + return root |
| 447 | + |
| 448 | + |
405 | 449 | def list_to_tree( |
406 | 450 | paths: list, |
407 | 451 | sep: str = "/", |
|
0 commit comments