How to read a list which is in list format in a text file in Python

强颜欢笑 提交于 2019-12-12 03:18:42

问题


I have this list in a txt file:

[1, "hello", {"Name": "Tom"}, [2, 3, "hello_hello"], (800, 600)]

There are an int, a str, a dict, a list and a tuple (not that it was really the matter).

I'd like to read this like this was a list (as it really is) not like one string.

I'd like to get a result like:

elem[0] = 1
elem[1] = "hello"
elem[2] = {"Name": "Tom"}
elem[3] = [2, 3, "hello_hello"]
elem[4] = (800,600)

Also it would be really nice if the dictionary evaluated eval() immediately, but that's not really the point.


回答1:


As indicated by @AvinashRaj in the comments, you can use the ast module (ast: Abstract Syntax Trees):

import ast

print ast.literal_eval('[1, "hello", {"Name": "Tom"}, [2, 3, "hello_hello"], (800, 600)]')

Output:

[1, 'hello', {'Name': 'Tom'}, [2, 3, 'hello_hello'], (800, 600)]

This should be the exact result (elem) you are expecting.




回答2:


I'd consider it a json.

import json
my_list = json.load(my_str_list)


来源:https://stackoverflow.com/questions/32114257/how-to-read-a-list-which-is-in-list-format-in-a-text-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!