如何在Python中读取文本文件中列表格式的列表 [英] How to read a list which is in list format in a text file in Python

查看:1255
本文介绍了如何在Python中读取文本文件中列表格式的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在txt文件中有此列表:

I have this list in a txt file:

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

有一个int,一个str,一个dict,一个list和一个tuple(不是真的).​​

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.

我想要一个类似的结果

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

如果字典立即对eval()进行评估,那将非常好,但这不是重点.

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

推荐答案

如注释中@AvinashRaj所示,您可以使用

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)]')

输出:

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

这应该是您期望的准确结果(elem).

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

这篇关于如何在Python中读取文本文件中列表格式的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆