簡體   English   中英

如何在Python中讀取文本文件中列表格式的列表

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

我在txt文件中有此列表:

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

有一個int ,一個str ,一個dict ,一個list和一個tuple (不是真的)。

我想讀這篇文章,就像是一個列表(實際上是一個列表),而不是一個字符串一樣。

我想要一個類似的結果:

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

如果字典立即對eval()進行求值也將是非常好的,但這並不是重點。

如注釋中@AvinashRaj所示,您可以使用ast模塊 (ast:抽象語法樹):

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 )。

我認為這是一個json。

import json
my_list = json.load(my_str_list)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM