Reputation: 29
I am doing a project for school and in order to even get started I have to find a way to convert a line in a text file to list. I know how to do this normally (for example if I'm given 1 2 3 4 5 6) but the text file I given is a binaryTree (including the characters '[' and ','). The actual text file is below.
[3, [9, [11, [4,[],[]], []], [] ], [7 , [], [6,[],[]]] ]
[3, [5, [4,[],[]], [8,[],[]]] , [7, [9,[],[]], [6,[],[]]]]
["alpha", ["berries", ["carrots", ["diamonds", ["edward",[],[]],[]],[]],[]],[]]
[7,[3,[2,[9,[],[]],[11,[1,[],[]],[]]],[]],[4,[5,[],[]],[8,[12,[13,[],[]],[0,[],[]]],[]]]]
[99, [], []]
Whenever I do this the way I would for 1 2 3 4 5 6 and call myList[0] I do not get the root 3 (for the tree in the first line) but instead the call returns the fist bracket '['. Can some one please show my the method to convert each line above to a multi-deminial list of represent a tree.
Upvotes: 0
Views: 136
Reputation: 76234
You can use ast.literal_eval
to turn strings into other built-in data types:
>>> import ast
>>> line = "[3, [9, [11, [4,[],[]], []], [] ], [7 , [], [6,[],[]]] ]"
>>> myList = ast.literal_eval(line)
>>> myList
[3, [9, [11, [4, [], []], []], []], [7, [], [6, [], []]]]
>>> myList[0]
3
Upvotes: 3