python - 如何将字符串转换为数字列表
问题描述
我在 Python 中将列表从字符串转换为数字时遇到问题。
我读了一个文件,需要从中提取坐标数据。
该文件包含以下坐标:
(-5 -0.005 -5)
(-4.9 -0.005 -5)
(-4.8 -0.005 -5)
(-4.7 -0.005 -5)
(-4.6 -0.005 -5)
(-4.5 -0.005 -5)
(-4.4 -0.005 -5)
(-4.3 -0.005 -5)
(-4.2 -0.005 -5)
(-4.1 -0.005 -5)
首先,我读取文件并使用以下代码获取坐标:
f = open("text.txt", 'r')
if f.mode == 'r':
contents = f.readlines()
之后,如果我调用内容 [0],它会将 (-5 -0.005 -5) 显示为字符串。
我尝试操纵内容。
coor = contents[0] # picking 1 list of coordinates
allNumber = coor[1:-2] # delete the open and close brackets
print(list(map(int, allNumber))) # hopefully get the integers mapped into x, y, and z coordinates :(
我得到这样的结果:
ValueError: invalid literal for int() with base 10: '-'
我想要这样的东西,[-5, -0.005, -5]
这样我就可以提取其中的每个数字。
解决方案
data = []
with open('test.txt') as f: # Better way to work with files
lines = f.readlines()
for line in lines:
data.append(line.strip()[1:-1].split(", "))
之后数据将是列表列表,因此您可以获取任何元素data[index_of_the_line][index of the elemnt]
推荐阅读
- javascript - 使用 jsp 和 codemirror js lib 时出现 Uncaught SyntaxError: Invalid or unexpected token
- java - 如何将现有的 SQLite3 数据库导入 Room?
- postgresql - 为什么 postgres 会扫描所有表?
- python-3.x - Struct.error: unpack 需要 16 字节的缓冲区
- c# - 我是否正忙于提出多个请求?
- java - Hashmap 将专辑名称与专辑名称联系起来?
- json - 如何在 Golang 中获取 JSON 唯一字段的名称和深度嵌套的子字段的值?
- html - Scrapy在页面上找不到表格
- ruby - 找不到杰基尔
- javascript - 商店的 React/Redux props 属性未定义