Python - 列出函数值的组合对

时间:2017-03-23 20:06:29

标签: python python-2.7 combinations

我有四个坐标的组合,我试图找到每个坐标之间的距离。我已经能够完成这个,但我无法让我的程序列出对应于每个距离的坐标对。

import itertools
import math
point1 = (1,1,0.5)
point2 = (3,3,1)
point3 = (2,0.5,2)
point4 = (0.5,2,1)

points = [(point1),(point2),(point3),(point4)]
pointsPairs = itertools.combinations(points, 2)
for pair in pointsPairs:
 x1 = pair[0][0]
 y1 = pair[0][1]
 z1 = pair[0][2]
 x2 = pair[1][0]
 y2 = pair[1][1]
 z2 = pair[1][2]

"""Define the values for the distance between the atoms"""
def calculate_distance(x1,y1,x2,y2,z1,z2):
   dist=math.sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2-z1)**2)
   return dist
d=calculate_distance(x1,y1,x2,y2,z1,z2)
print d

我得到了

2.87228132327
1.87082869339
1.22474487139
2.87228132327
2.69258240357
2.34520787991

我想找到一种方法来制作像

这样的东西
 "Distance between point1 and point2 is"
  2.87228132327
每个组合

2 个答案:

答案 0 :(得分:1)

在循环之前,您可以创建一个字符,其中坐标为键,名称(使用索引从1开始)为值:

points_dict = {k:"point_{}".format(i) for i,k in enumerate(points,1)}

并在循环中,只需从combinations生成的坐标中获取名称:

print("computing distance between {} and {}".format(points_dict[pair[0]],points_dict[pair[1]]))

通过这样做,我得到了

computing distance between point_1 and point_2
2.8722813232690143
computing distance between point_1 and point_3
1.8708286933869707
computing distance between point_1 and point_4
1.224744871391589
computing distance between point_2 and point_3
2.8722813232690143
computing distance between point_2 and point_4
2.692582403567252
computing distance between point_3 and point_4
2.345207879911715

答案 1 :(得分:1)

基本上,您所使用的数据结构中不包含您的点的名称。我稍微修改了你的代码以包含点的名称:

import itertools
import math

"""Define the values for the distance between the atoms"""
def calculate_distance(x1,y1,x2,y2,z1,z2):
   dist=math.sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2-z1)**2)
   return dist

point1 = (1,1,0.5,'point1')
point2 = (3,3,1,'point2')
point3 = (2,0.5,2,'point3')
point4 = (0.5,2,1,'point4')

points = [(point1),(point2),(point3),(point4)]
pointsPairs = itertools.combinations(points, 2)
for pair in pointsPairs:
 x1 = pair[0][0]
 y1 = pair[0][1]
 z1 = pair[0][2]
 x2 = pair[1][0]
 y2 = pair[1][1]
 z2 = pair[1][2]
 d=calculate_distance(x1,y1,x2,y2,z1,z2)
 p1=pair[0][3]
 p2=pair[1][3]
 print "The distance between '%s' and '%s' is" % ( p1, p2 ) 
 print d

这给出了以下结果:

The distance between 'point1' and 'point2' is
2.87228132327
The distance between 'point1' and 'point3' is
1.87082869339
The distance between 'point1' and 'point4' is
1.22474487139
The distance between 'point2' and 'point3' is
2.87228132327
The distance between 'point2' and 'point4' is
2.69258240357
The distance between 'point3' and 'point4' is
2.34520787991