[英]How to convert string to list of numbers
I have a problem of converting list from string to numbers in Python. 我在Python中将列表从字符串转换为数字时遇到问题。
I read a file and need to extract the coordinate data from it. 我读取了一个文件,需要从中提取坐标数据。
The file contains these coordinates: 该文件包含以下坐标:
(-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)
First, I read the file and get the coordinates using this code: 首先,我读取文件并使用以下代码获取坐标:
f = open("text.txt", 'r')
if f.mode == 'r':
contents = f.readlines()
After that, if i called contents[0], it showed (-5 -0.005 -5) as a string. 之后,如果我调用contents [0],它将显示为(-5 -0.005 -5)作为字符串。
I tried manipulating the contents. 我试图处理内容。
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 :(
I got results like this: 我得到这样的结果:
ValueError: invalid literal for int() with base 10: '-'
I want something like [-5, -0.005, -5]
so I can extract each number inside it. 我想要类似[-5, -0.005, -5]
东西[-5, -0.005, -5]
这样我就可以提取其中的每个数字。
You can do it like this: 您可以这样做:
with open('test.txt') as f:
lines = (line.strip()[1:-1] for line in f)
values = (tuple(map(float, line.split())) for line in lines)
data = list(values)
print(data)
# [(-5.0, -0.005, -5.0), (-4.9, -0.005, -5.0), (-4.8, -0.005, -5.0),
# (-4.7, -0.005, -5.0), (-4.6, -0.005, -5.0), (-4.5, -0.005, -5.0),
# (-4.4, -0.005, -5.0), (-4.3, -0.005, -5.0), (-4.2, -0.005, -5.0), (-4.1, -0.005, -5.0)]
Use with open()...
to make sure that the file gets closed whatever happens. with open()...
以确保无论发生什么情况文件都会关闭。
lines
is a generator, it iterates on the lines of the file and yields each line stripped of the newline, after cutting the first and last character, the parenthesis. lines
是一个生成器,它在文件的各行上进行迭代,并在切掉第一个和最后一个字符(括号)之后产生从换行符中剥离的每一行。
values
generate a tuple for each of these cleaned lines, by splitting it and turning the values to floats, as they aren't all integers. values
为这些清理后的每一行生成一个元组,方法是将其拆分并将值转换为浮点数,因为它们并非全都是整数。
We then make a list out of it. 然后,我们从中列出一个清单。
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(", "))
after that data will be list of lists, so you can get any element with data[index_of_the_line][index of the elemnt]
之后的数据将是列表列表,因此您可以使用data[index_of_the_line][index of the elemnt]
获取任何元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.