首页 > 解决方案 > 将字符串列表转换为指定格式的原始 python 列表

问题描述

我正在从文本文件中读取一行:文本文件如下所示:

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

给出错误。

请帮忙。

标签: pythonstringpython-3.xlist

解决方案


冒号不是 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]

推荐阅读