Python-列出功能值的组合对 [英] Python - list the combination pair for a function value
本文介绍了Python-列出功能值的组合对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有四个坐标的组合,并且我试图找到每个坐标之间的距离。我已经能够完成此操作,但是我无法让我的程序列出与每个距离相对应的坐标对。
I have a combination of four coordinates, and I am trying to find the distance between each coordinates. I have been able to complete this, but I cannot get my program to list the coordinate pair that corresponds to each distance.
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
我想找到一种制作类似东西的方法
I would like to find a way to make something like
"Distance between point1 and point2 is"
2.87228132327
每种组合
推荐答案
在循环之前,您可以创建一个字典,将坐标作为键,并将名称(使用从1开始的索引)作为值:
Before your loop, you could create a dictionary with coordinates as key and the name (using indexes starting at 1) as value:
points_dict = {k:"point_{}".format(i) for i,k in enumerate(points,1)}
,然后在循环中,只需从组合
:
and in your loop, just fetch the name from the coordinates yielded by 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
这篇关于Python-列出功能值的组合对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文