Skip to content

Instantly share code, notes, and snippets.

@eric-wieser
Created July 18, 2017 23:04
Show Gist options
  • Select an option

  • Save eric-wieser/1cc4b1b8a2696dd3450a4397ee2689c6 to your computer and use it in GitHub Desktop.

Select an option

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
#! 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