在距离矩阵中查找值的索引?

从 461 个 X、Y 和 Z 坐标列表中,我使用 SciPy 创建了一个距离矩阵,如下所示


[[ 0.          3.78112691  6.55159315 ... 63.40661118 62.2923149

  64.71125443]

 [ 3.78112691  0.          3.76986434 ... 60.79913069 59.55251531

  61.87364432]

 [ 6.55159315  3.76986434  0.         ... 61.12392086 59.65959803

  61.94572052]

 ...

 [63.40661118 60.79913069 61.12392086 ...  0.          3.8003808

   5.63044026]

 [62.2923149  59.55251531 59.65959803 ...  3.8003808   0.

   3.82889361]

 [64.71125443 61.87364432 61.94572052 ...  5.63044026  3.82889361

   0.        ]]

我还编写了代码,允许用户从距离矩阵中提取小于或等于某个值的值,然后将其写入文本文件


radius = int(input("Enter the radius threshold for contact (Angstrom): "))



###########This code will extract every pair <= radius##################

f = open('contact.txt', 'w')


for i in distance_matrix:

    for j in i:

        if j <= radius:

            if j != 0:

                f.write(str(j) + '\n')


print("File contact.txt written")

#########################################################################

文本文件 (contact.txt) 只是一长串值 <= 到用户指定的值。有没有办法也写出这些值来自哪一对索引?例如,如果在 x 轴上的索引 b 和 y 轴上的值 c 的交点处找到值“a”,是否可以将其添加到输出文本文件中?


翻过高山走不出你
浏览 260回答 2
2回答

慕后森

根据评论,您可以使用 enumerate 这相当于zip( range( len(vec)), vec)去做这个:f = open('contact.txt', 'w')for n1, i in enumerate(distance_matrix):&nbsp; &nbsp; for n2 ,j in enumerate(i):&nbsp; &nbsp; &nbsp; &nbsp; if j <= radius:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if j != 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; f.write(str(j) + '\n')print("File contact.txt written")其中 n1 和 n2 是您的索引

当年话下

你可以使用np.whereindices = np.where((distance_matrix <= radius) & (distance_matrix != 0))row_col_vals = list(zip(*indices, distance_matrix[indices]))&nbsp; # gives you a list or (row, col, value) tuples例如,如果radius = 5和distance_matrix =&nbsp; np.array([[2, 6], [0, 3]])然后row_col_vals = [(0, 0, 2), (1, 1, 3)]写入文件:f = open('contact.txt', 'w')for row, col, val in row_col_vals:&nbsp; &nbsp; print(row, col, val, file=f)f.close()哈。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python