#turns the text file into a list with each coordinates on a seperate line.
with open('AV.txt', 'r') as file:
file_data = file.read()
file_data = file_data.replace('],', ']\n')
with open('AV.txt', 'w') as file:
file.write(file_data)
#puts the vertices into an array
array = []
with open('AV.txt') as f:
for line in f:
array.append(line.strip("\n"))
#individual vertices according to their axis
x_array = [i[1] for i in array]
y_array = [i[7] for i in array]
z_array = [i[13] for i in array]
#Finds the maximum, minimum, and median for the x vertices
max_x = -1000000000000
min_x = 1000000000000
x_array_sorted = sorted(x_array)
length_x_array = len(x_array_sorted)
half_point_x = length_x_array//2
median_x = x_array_sorted[half_point_x]
n = 0
for q in x_array:
if float(x_array[n]) > float(max_x):
max_x = x_array[n]
if float(x_array[n]) < float(min_x):
min_x = x_array[n]
n = n + 1
当我运行此代码时,出现此值错误
ValueError: could not convert string to float: '-'.
何时到达
if float(x_array[n]) > float(max_x):
我不知道如何使我的代码接受某些坐标为负数,因此在它们前面加一个“-”。有任何想法吗?谢谢。
正在打开并读取的文件中的示例文本行:[27.36,-31.24,26.03]
答案 0 :(得分:1)
要解决您遇到的问题,您只需将列表推导转换为整数即可。
#individual vertices according to their axis
x_array = [int(i[1]) for i in array]
y_array = [int(i[7]) for i in array]
z_array = [int(i[13]) for i in array]
上面的代码遍历array
3次以创建三个列表项。我建议您将其转换为这样的单个循环。
for i in array:
x_array.append(int(i[1])
y_array.append(int(i[7])
z_array.append(int(i[13])
此外,我是否建议您通过处理内存中的值来最小化I / O。
例如:您可以将以下代码更改为更少的行:
如果file_data是您从AV.txt
中读取的信息,那么下面的三行代码将为您提供所需的列表。
file_data = '[1, 2, 3, 4, 5][20, 59, 60, 80][30, 15, 16]'
file_data = file_data.replace(']',']\n')
arr = file_data.strip('\n')
print (arr)
输出为:
[1, 2, 3, 4, 5]
[20, 59, 60, 80]
[30, 15, 16]
您可以将上面的大多数代码替换为上面的代码。
#turns the text file into a list with each coordinates on a seperate line.
with open('AV.txt', 'r') as file:
file_data = file.read()
file_data = file_data.replace('],', ']\n')
with open('AV.txt', 'w') as file:
file.write(file_data)
#puts the vertices into an array
array = []
with open('AV.txt') as f:
for line in f:
array.append(line.strip("\n"))