简体   繁体   中英

converting a text file containing a tree to a list

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.

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

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