我正在从文本文件中读取一行:文本文件如下所示:
2 [209:0.3720511,256:0.3525813,300:0.3466443,148:0.3456179,246:0.3443979,267:0.3425797,126:0.3397026,10:0.3379505,266:0.3357508,301:0.334953]
我正在尝试在包含值[209:0.3720511,256:0.3525813,300:0.3466443,148:0.3456179,246:0.3443979,267:0.3425797,126:0.3397026,10:0.3379505,266:0.3357508,301:0.334953]
的列表中转换[209,256,300,148,246,267...]
我点击了以下链接:Convert string representation of list to list
这是我的代码,但是不起作用:
with open("file.txt", "r") as text_file:
for line in itertools.islice(text_file, 19, 20): # only one line
print(ast.literal_eval(line.split(" ")[1]))
给出错误。
请帮助。
答案 0 :(得分:2)
冒号不是Python中有效数字的一部分。因此,ast.literal_eval
是不合适的。
相反,您可以结合使用列表理解和str.split
和切片:
x = '[209:0.3720511,256:0.3525813,300:0.3466443,148:0.3456179,246:0.3443979,267:0.3425797,126:0.3397026,10:0.3379505,266:0.3357508,301:0.334953]'
res = [int(i.split(':')[0]) for i in x[1:-1].split(',')]
# [209, 256, 300, 148, 246, 267, 126, 10, 266, 301]
答案 1 :(得分:0)
如果我输入的是 exact 字符串,则您提供了以下信息:
执行文字评估 literal_eval =输出python字典
line_fixed = literal_eval(line.split(' ')[-1].replace('[', '{').replace(']', '}'))
print (line_fixed.keys() )
print (line_fixed.values() )