首页 > 解决方案 > 如何将字符串转换为数字列表

问题描述

我在 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]这样我就可以提取其中的每个数字。

标签: pythonpython-3.xparsing

解决方案


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]


推荐阅读