Created
July 18, 2017 23:04
-
-
Save eric-wieser/1cc4b1b8a2696dd3450a4397ee2689c6 to your computer and use it in GitHub Desktop.
Print out a nested list as a tree with line-drawing characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #! python3 | |
| def first_then(first, then): | |
| yield first | |
| while True: | |
| yield then | |
| prefix_one = lambda: first_then('━━', ' ') | |
| prefix_many_first = lambda: first_then('┳━', '┃ ') | |
| prefix_many_rest = lambda: first_then('┣━', '┃ ') | |
| prefix_many_last = lambda: first_then('┗━', ' ') | |
| def tree_lines(x): | |
| if type(x) is tuple: | |
| if len(x) == 1: | |
| # singular tuple | |
| for p, l in zip(prefix_one(), tree_lines(x[0])): | |
| yield p + l | |
| else: | |
| first, rest, last = x[0], x[1:-1], x[-1] | |
| # first entry | |
| for p, l in zip(prefix_many_first(), tree_lines(first)): | |
| yield p + l | |
| # middle entries | |
| for y in rest: | |
| for p, l in zip(prefix_many_rest(), tree_lines(y)): | |
| yield p + l | |
| # last entries | |
| for p, l in zip(prefix_many_last(), tree_lines(last)): | |
| yield p + l | |
| else: | |
| yield str(x) | |
| if __name__ == '__main__': | |
| x = ((('A','B'),('C','D')),'E') | |
| for l in tree_lines(x): | |
| print(l) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment