迭代Python对象

时间:2013-01-24 23:34:28

标签: python algorithm

我正在尝试编写一个基于zipcode,lat和lng计算某个公式的程序。

我最初的想法是为每个邮政编码创建一个对象。

class destination():
def __init__(self, zipcode, count):
    self.zipcode = zipcode
    self.count = count

def getCount(self):
    return self.count

def getZip(self):
    return self.zipcode

def getLatitude(self):
    return self.lat 

def getLongitude(self):
    return self.lng 

def __str__(self):
    return "%s at %s , %s" % (self.zipcode, self.lat, self.lng)

def getCoords(self):
    '''
    Must be called before getLatitude or get Longitude
    '''
    self.place, (self.lat, self.lng) = gn.geocode(str(self.zipcode))  
    self.city = self.place.split(",",1)
    self.name =  self.city[0]
    self.value = str(count)+","+self.name

    return self.value

这很好,因为我可以成功迭代列表并创建对象并从中提取必要的信息

zipList = ['54971','46383','90210']

for i in zipList:
    i = destination(i,count)
        count += 1

将返回

1,Ripon
-88.8359447
43.8422049
2,Valparaiso
-87.0611412
41.4730948
3,Beverly Hills
-118.4003563
34.0736204

我似乎无法理解的是如何设置程序,以便它遍历调用hasrsine函数的列表,并为每个项目提供正确的信息。

def haversine(latStart,lonStart,latEnd,lonEnd):

实施例: 如果我的清单是

zipList = ['54971','46383','90210']

然后它会计算54971到46383,54971到90210和46383到90210

4 个答案:

答案 0 :(得分:3)

尝试使用itertools,combinations function可能就是你想要的。

答案 1 :(得分:3)

从列表中询问所有邮政编码对,并使用它们:

import itertools

for start, stop in itertools.combinations(zipList, 2):
    print start, stop
    # now pass start, stop to your function

答案 2 :(得分:0)

您可以创建目标对象列表并获取已创建列表的组合,并通过hasrsine函数迭代返回的生成器。

dests = []
for i in zipList:
    dests.append(destination(i,count))
    count += 1

dests_gen = itertools.combinations(dests, 2)
for dest_typle in dests_gen:
    pass

答案 3 :(得分:0)

简短回答:

for a, b in ( (a, b) for a in zipList for b in zipList):
    print (a, b, distance (a, b) )

一些评论:如果你把它作为一个类变量,你不需要手动控制“count”。您可以使用属性按需对地点进行地理定位(即首次访问lat或lon时)。如果属性是公共的,那么你真的不需要getter方法(除非API需要这个)。也许是这样的。

#! /usr/bin/python3.2

def haversine (latStart,lonStart,latEnd,lonEnd): return 42

class Destination():
    count = 0

    def __init__(self, zipcode):
        self.zipcode = zipcode
        self.count = self.__class__.count
        self.__class__.count += 1
        self.__coords = None

    @property
    def latitude (self):
        if not self.__coords: self.__locate ()
        return self.__coords [0]

    @property
    def longitude (self):
        if not self.__coords: self.__locate ()
        return self.__coords [1]

    def __str__(self):
        return "%s at %s , %s" % (self.zipcode, self.latitude, self.longitude)

    def __locate (self):
        '''
        Will be called automatically before getLatitude or get Longitude
        '''
        self.place, self.__coords = gn.geocode (str (self.zipcode) )  
        self.city = self.place.split (",",1)
        self.name =  self.city [0]

    def distance (self, other):
        return haversine (self.latitude, self.longitude, other.latitude, other.longitude)