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

2024-10-04 09:22:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用一个.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]")


Tags: 文件oftexttxtinputdataobjectline
2条回答

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

使用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]

相关问题 更多 >