python - 将字符串列表转换为指定格式的原始 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]))
给出错误。
请帮忙。
解决方案
冒号不是 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]
推荐阅读
- javascript - ISSLive Telemetry: Locking Protocol SQLite3 C++ error on query, with Javascript code update the same SQLite3 database, all on WSL
- azure - 如何在 azure-cosmosdb (Document DB) 中保持文档创建幂等性?
- python-3.x - 使用 CPLEX 约束规划的矩形调度程序
- javascript - 如何获取悬停时出现的元素的宽度
- bash - 在双引号内转义单引号内的单引号
- ios - 导航时关闭视图控制器
- kotlin - 在 Kotlin 代码中使用 NotBlank 注释不起作用
- r - 使用 facet_wrap 在 ggplot 中绘制全范围的分位数回归
- r - is there a method to get frequency distribution different columns in R
- sql - 如果同月数据阶段或sql的费率不同,如何解决?