从文件中读取元组并将其转换为列表

时间:2021-03-01 09:15:00

标签: python python-3.x list file tuples

我想从文件中读取元组并将其转换为列表。

该文件包含:(1,2,3)

我的代码:

with open('scores.txt','r+') as scores:
    score_file=list(scores.read())
    print(score_file)

输出是:['(', '1', ',', '2', ',', '3', ')'] 但我想要的是:[1,2,3] 我该怎么做:

3 个答案:

答案 0 :(得分:2)

由于 scores.read() 返回类型为 str 的对象,使用 list(scores.read())str 对象被分解为具有单个字符的 list

您可以使用 ast.literal_eval() 转换为正确的数据类型,然后转换为列表:

import ast
with open('scores.txt','r+') as scores:
    score_file = scores.read()
    score_file = list(ast.literal_eval(score_file))
    
    print(score_file)
    print(type(score_file))

输出:

[1, 2, 3]
<class 'list'>

答案 1 :(得分:0)

你可以这样做

lst = []

with open('scores.txt','r+') as scores:
    score_file = scores.read()
    for item in score_file:
        if item != '(' and item != ')' and item != ',':
            lst.append(int(item))

print(lst)

它遍历分数并将它们作为整数添加到列表中。

答案 2 :(得分:0)

如果你不想导入模块,你可以使用列表理解。对于分数中的每个分数,您可以去掉括号并在逗号上分开。然后转换为 int。

with open('scores.txt','r+') as scores:
    for score in scores:
        print([int(i) for i in score.strip('()').split(',')])

>>> [1, 2, 3]
相关问题