2 回答
TA贡献1835条经验 获得超7个赞
尝试这个:
with open('Data.txt','r') as file:
result = [tuple(map(int, line.strip(' \n()').split(','))) for line in file]
print(result)
[(3, 9, 16, 40, 41, 44),
(15, 25, 26, 41, 45, 46),
(1, 6, 21, 27, 39, 48),
(7, 20, 26, 29, 39, 42),
(17, 23, 25, 29, 30, 43)]
我相信这是您想要的输出。
第一步是去除空格和括号 ( line.strip(' \n()'))。然后,将其拆分为逗号 ( .split(','))列表,然后将字符串列表转换为整数元组 ( tuple(map(int, ))。
TA贡献2065条经验 获得超14个赞
这是使用的简单方法ast.literal_eval():
from ast import literal_eval
with open('Data.txt','r') as file:
data = [literal_eval(line) for line in file]
print(data)
打印输出:
[(3, 9, 16, 40, 41, 44), (15, 25, 26, 41, 45, 46), (1, 6, 21, 27, 39, 48), (7, 20, 26, 29, 39, 42), (17, 23, 25, 29, 30, 43)]
添加回答
举报