我已经解决了这个问题,经过几个小时的尝试,我想问一个比我更有经验的人(这应该没问题因为我是初学者)。
我的input.xyz文件有八个点,看起来像这样:
15.486586, 46.798954, -6.232800, 15.445764, 46.807576, -6.249205, -0.040822,0.008622, -0.016405, 0.044832;
6.233575, 48.083754, -4.223557, 6.187027, 48.090785, -4.243389, -0.046548, 0.007031, -0.019832, 0.051083;
-2.159452, 40.818712, -3.104244, -2.200572, 40.818489, -3.120266, -0.041120,-0.000223, -0.016022, 0.044132;
45.554111, 131.689322, 1.525740, 45.452954, 131.721406, 1.483290, -0.101157,0.032084, -0.042450, 0.114298;
28.315109, 146.107918, 2.897549, 28.235633, 146.131800, 2.864060, -0.079476, 0.023882, -0.033489, 0.089489;
7.303209, 138.223347, 4.702106, 7.250850, 138.242379, 4.679564, -0.052359, 0.019032, -0.022542, 0.060098;
-32.211983, 148.909744, 12.919538, -32.279077, 148.907541, 12.876267,-0.067095, -0.002203, -0.043271, 0.079868;
-48.926024, 180.295215, 20.142896, -49.008547, 180.275117, 20.127614,-0.082523, -0.020098, -0.015282, 0.086299;
“;”分离每个点,一个点的前三个值是x,y和z值。所以我想用xyz值取三个点并用python将它们写在矩阵中。 这是我到目前为止所得到的:
# creating empty list for append
xyz_matrx = []
counter = 0
for line in xyz:
counter += 1
# counter to get only first three columns
if counter%4 == 0:
break
# deleting whitespaces and selecting wanted data
linevalues = line.strip().split(",")
x = (linevalues[0:1])
y = (linevalues[1:2])
z = (linevalues[2:3])
xyz_matrx.append(x)
#flatten because xyz_matrix is a list within list
# values converting into float64, because string won't work for following
#work
flattenedx = [val for sublist in xyz_matrx for val in sublist]
matr_flatx = [float(i) for i in flattenedx]
A_matrx = mat(matr_flatx)
有了这个,我得到一个1x3矩阵,其xyz点在矩阵中是水平的,但是我想在矩阵中有三列,它代表每个点和行代表xyz值,数据类型为float3的3x3矩阵。 如果我用索引改变一些东西,我只得到string88矩阵。 我可以为另外两个点创建另外两个列表,然后我有三个1x3矩阵但是“.append”不起作用,因为我没有二维矩阵?
我知道我的代码不是很有效但我希望有人能理解我的问题并且可以帮助我。
简短:我有一个输入.xyz文件,只有每个点的前三个值(x,y,z坐标)是相关的,我想要三个xyz点,它们的三个坐标分别是3x3矩阵(第一列垂直:第一个点,xyz,第二列垂直:第二个点,xyz,第三个列第三个点,xyz垂直向下),数据类型必须是float64。
答案 0 :(得分:0)
这是你可以做到的一种方式
# creating empty list for append
xyz_matrix = []
counter = 0
with open('input.xyz', 'r') as f:
for line in f:
# Add the first three values to the matrix
xyz_matrix.append(map(float, line.strip().split(",")[0:3]))
counter += 1
if counter == 3:
break
# Transpose
xyz_matrix = zip(*xyz_matrix)
print xyz_matrix
你最终得到了一个元组列表,但那应该没问题。
这更直接,但不太通用
# Creating an empty 2D list
xyz_matrix = [[], [], []]
counter = 0
with open('input.xyz', 'r') as f:
for line in f:
# Add the first three values to the matrix
values = map(float, line.strip().split(",")[0:3])
# Append x, y, z to each rows 0, 1, 2 respectively
for i in range(3):
xyz_matrix[i].append(values[i])
counter += 1
if counter == 3:
break
print xyz_matrix