将字符串列表转换为元组?

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