将值传递给函数

时间:2013-06-03 13:09:19

标签: python

这是我希望用来通过lat / long计算距离的函数

def calculateDistance( latOne, lonOne, latTwo, lonTwo ):
    from decimal import Decimal
    latOne, lonOne, latTwo, lonTwo = [Decimal(x) for x in (latOne, lonOne, latTwo,lonTwo)]
    DISTANCE_CONSTANT = 111120.0
    coLat = math.fabs(lonOne - lonTwo)
    alpha = 90 - latTwo
    beta  = 90 - latOne

    cosAlpha = math.cos(math.radians(alpha))
    cosBeta  = math.cos(math.radians(beta))
    sinAlpha = math.sin(math.radians(alpha))
    sinBeta  = math.sin(math.radians(beta))
    cosC     = math.cos(math.radians(coLat))

    cos_of_angle_a = (cosAlpha * cosBeta)
    cos_of_angle_b = (sinAlpha * sinBeta * cosC)
    cos_of_angle_c = cos_of_angle_a + cos_of_angle_b
    angle          = math.degrees(math.acos(cos_of_angle_c))
    distance       = angle * DISTANCE_CONSTANT
    return distance

如果我有一组lats和long列表,例如:

lat = ['200', '210', '240', '300'] 
long = ['10', '20', '30', '40']

latOne的已知坐标,lonOne,等于

lat = 100 
lon = 200 

有没有办法可以遍历列表并将它们应用到函数中?基本上,我想将latOnelonOne设置为始终等于已知坐标,然后循环遍历列表并将列表中的这些值提供给latTwolonTwo列表中的值。

简单地说,有没有办法将值传递给函数,然后返回距离并重做所有lat和long值?

例如:

latOne =100, lonOne = 200, latTwo = 200, lonOne = 10 
to function then return distance.
then run 
latOne =100, lonOne = 200, latTwo = 210, lonOne = 20 

等等,直到long和lat的所有列表值都输入到函数中。

2 个答案:

答案 0 :(得分:3)

你的意思是:

results = [CalculateDistance(100,200,lattwo,lontwo) 
           for lattwo,lontwo in zip(latOne,lonOne)]

答案 1 :(得分:1)

Python的zip函数结合了两个lists into a list of tuples。您可以迭代它以一次获得一对:

for latTwo, lonTwo in zip(lat, long):
  print calculateDistance(latOne, lonOne, latTwo, lonTwo )

以上只是打印结果。你可以用老式的方式生成数组:

out=[]
for latTwo, lonTwo in zip(lat, long):
  out.append(calculateDistance(latOne, lonOne, latTwo, lonTwo ))

或者您可以使用列表推导:

 [calculateDistance(latOne, lonOne, latTwo, lonTwo ) for latTwo, lonTwo in zip(lat, long)]