[英]convert a list of strings to tuples?
我正在嘗試使用 .txt 文件為我的游戲制作排行榜功能,但是在提取列表時,它將元組轉換為字符串
我有的代碼:
#USER INPUT__________________________________________________________
text=input("input: ")
#READING AND PRINTING FILE__________________________________________
a_file = open("textest.txt", "r")
list_of_lists = []
for line in a_file:
stripped_line = line.strip()
line_list = stripped_line.split()
list_of_lists.append(line_list)
a_file.close()
print(list_of_lists)
#INSERTING STUFF IN THE FILE_________________________________________
with open("textest.txt", "a+") as file_object:
file_object.seek(0)
data = file_object.read(100)
if len(data) > 0 :
file_object.write("\n")
file_object.write(text)
文件的內容是
['test1', 60]
['play 1', 5080]
['test2', 60]
['test3', 160]
['fake1', 69420]
但輸出給出("['test1', 60]","['play 1', 5080]","['test2', 60]","['test3', 160]","['fake1', 69420]")
使用ast.literal_eval()
將文件解析為列表。
import ast
with open("textest.txt", "r") as a_file:
list_of_lists = [ast.literal_eval(line) for line in a_file]
ast.literal_eval()
安全地計算表達式節點或包含 Python 文字的字符串。
import ast
data = ("['test1', 60]","['play 1', 5080]","['test2', 60]","['test3', 160]","['fake1', 69420]")
[tuple(ast.literal_eval(x)) for x in data]
輸出:
[('test1', 60),
('play 1', 5080),
('test2', 60),
('test3', 160),
('fake1', 69420)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.