繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM