在Python

时间:2018-03-13 02:32:18

标签: python loops permutation

我想以所有可能的组合计算所有坐标(x1,y1)和(x2,y2)的斜率,而不重复任何。有什么方法可以自动完成吗?

#parameters
x1 = 10.18182
x2 = 13.14286
y1= (0.30097,0.31036,0.3911,0.34255,0.198374,0.398574,0.377364,0.2428,0.319312,0.13338,0.228027,0.242637,0.326533)
y2= (0.536551,0.450893,0.299292,0.286737,0.438004,0.272566,0.42541,0.430583,0.282882,0.285569,0.286261,0.439658)

#Slope
m0=(y2[0]-y1[0])/(x2-x1)
m1=(y2[1]-y1[0])/(x2-x1) 
m2=(y2[2]-y1[0])/(x2-x1)
...
mn=(y2[11]-y1[12])/(x2-x1)

谢谢!

3 个答案:

答案 0 :(得分:2)

一行代码:m_list = [(y2_val-y1_val)/(x2-x1) for y1_val in y1 for y2_val in y2]

x1 = 10.18182
x2 = 13.14286
y1 = (0.30097,0.31036,0.3911,0.34255,0.198374,0.398574,0.377364,0.2428,0.319312,0.13338,0.228027,0.242637,0.326533)
y2 = (0.536551,0.450893,0.299292,0.286737,0.438004,0.272566,0.42541,0.430583,0.282882,0.285569,0.286261,0.439658)
m_list = [(y2_val-y1_val)/(x2-x1) for y1_val in y1 for y2_val in y2]
print m_list

答案 1 :(得分:2)

使用itertools.product

import itertools

yourlist=[(s2-s1)/(x2-x1) for s2,s1 in itertools.product(y2,y1)]

答案 2 :(得分:1)

x1 = 10.18182
x2 = 13.14286
y1= (0.30097,0.31036,0.3911,0.34255,0.198374,0.398574,0.377364,0.2428,0.319312,0.13338,0.228027,0.242637,0.326533)
y2= (0.536551,0.450893,0.299292,0.286737,0.438004,0.272566,0.42541,0.430583,0.282882,0.285569,0.286261,0.439658)


def slope(x1, y1, x2, y2):
        return (y2-y1)/(x2-x1)

    for y in y1:
        for y_ in y2:
            print(x1,y,x2,y_)