Python循环两次附加同一对象 [英] Python loop appending same object twice

查看:83
本文介绍了Python循环两次附加同一对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注YouTube视频通过数据黑客学习Python ,并在通过添加类来学习Python OOP的所有来龙去脉,这是一种传统"内联方式.基本上,视频中的那个人让您掌握了芝加哥公交线路的路线,对其进行了解析,并通过比较经纬度,时间,距离等来找到他的朋友将行李箱留在了哪辆公交车上.

我正在使用的XML文件具有很多这样的值:

 < bus>< id> 1867</id>< rt> 22</rt>< d>北界</d>< dd>北行</dd>< dn> N</dn>< lat> 41.89167051315307</lat>< lon> -87.6297836303711</lon>< pid> 5421</pid>< pd>北行</pd>< run> P258</run>< fs>霍华德</fs>< op> 30090</op>< dip> 8858</dip>< bid> 7323012</bid>< wid1> 0P</wid1>< wid2> 258</wid2></bus> 

从那里,我需要找到哪辆巴士的纬度位于他的位置以北(在该类中定义,在本例中为模拟题).在这些节点上,我正在创建一个 Bus 对象,如下所示:

  class总线:#原始XML节点__xml =无#我们的属性字典可在此对象上隐藏get()函数__tree = {}def __init __(self,busxml):self .__ xml = busxml用于busxml中的e:self .__ tree [e.tag] = busxml.findtext(e.tag)def gettree():返回self .__ tree#尝试返回prop,或返回Nonedef get(自己,道具):尝试:返回self .__ tree [prop]除了KeyError:返回-1def getall():返回self .__ tree 

从主"文件中,我遍历这些值并根据 lat 节点的文本值附加匹配项:

 #__getRouteData()是url打开和写入功能,可以正常工作.#解析器是xml.etree.ElementTree解析类如果self .__ getRouteData()==真:xmlParser =解析器(self .__ xmlFile)busses = xmlParser.getnodes()匹配= []#遍历所有对于busTree在公交车上:公交车=公交车(busTree)如果float(bus.get('lat'))>自我.__ lat:matchs.append(公共汽车)打印'appending',bus.get('id')比赛中的巴士:打印bus.get('id') 

我遇到的障碍位于上面的第二个 for 循环中.在第一个循环中,输出告诉我一切运行良好.第二个输出相同的值两次.它使我想起Javascript for()循环的行为,在没有闭包的情况下,仅对最后一个值起作用.我的控制台输出如下:

 追加1784附加405740574057 

看...这是告诉我要将唯一的总线添加到我的 matches 列表中,但是当我遍历 matches 列表时,它只会给我一辆总线./p>

第二个循环告诉我一些时髦的内容:

 打印匹配",匹配比赛中的巴士:打印bus.get('id')#匹配[<位于0xb6f92b8c的busutils.Bus实例,<位于0xb6f92d0c的busutils.Bus实例]]# 4057#4057 

列表的输出向我显示了列表中对象的不同哈希值(...对吗?),因此表示它们是两个不同的对象,因此具有不同的数据,但是循环播放效果不佳

很显然,我只是接触python,但是有Java,Javascript,PHP等方面的经验,所以我不确定这些简单循环中缺少什么.

谢谢!

解决方案

这是因为您在Bus类上使用了类变量.使它们成为实例变量(在 __ init __ 中创建).

I'm following the YouTube video Learn Python through Data Hacking and am expanding on the sort of "legacy" inline way by adding classes to learn all the ins and outs of Python OOP. Basically the guy in the video has you grab the Chicago bus line's route, parse it, and find which bus his friend left his suitcase on by comparing lat, long, time, distace, etc.

The XML file I'm working with has a bunch of values like so:

<bus>
    <id>1867</id>
    <rt>22</rt>

    <d>North Bound</d>
    <dd>Northbound</dd>
    <dn>N</dn>
    <lat>41.89167051315307</lat>
    <lon>-87.6297836303711</lon>
    <pid>5421</pid>
    <pd>Northbound</pd>
    <run>P258</run>
    <fs>Howard</fs>
    <op>30090</op>
    <dip>8858</dip>
    <bid>7323012</bid>
    <wid1>0P</wid1>
    <wid2>258</wid2>                
</bus>

From there, I need to find which bus' latitude are north from his position (defined in the class, moot for this example). From those nodes, I'm creating a Bus object like so:

class Bus:
    # The original XML node
    __xml = None

    # Our dictionary for properties to shadow a get() function on this object
    __tree = {}

    def __init__(self, busxml):
        self.__xml = busxml
        for e in busxml:
            self.__tree[e.tag] = busxml.findtext(e.tag)

    def gettree(self):
        return self.__tree

    # Tries to return prop, or returns None
    def get(self, prop):
        try:
            return self.__tree[prop]
        except KeyError:
            return -1
    def getall(self):
        return self.__tree

From the "main" file, I'm looping through the values and appending matches based on the lat node's text value:

# __getRouteData() is the url open and write function, works fine.
# parser is the xml.etree.ElementTree parse class
if self.__getRouteData() == True:
    xmlParser = parser(self.__xmlFile)
    busses = xmlParser.getnodes()

    matches = []
    # loop over all
    for busTree in busses:
        bus = Bus(busTree)

        if float(bus.get('lat')) > self.__lat:
            matches.append(bus)
            print 'appending', bus.get('id')

    for bus in matches:
        print bus.get('id')

The snag I'm hitting is in the second for loop above. In the first loop, the output is telling me things are working well. The second one outputs the same value twice. It reminds me of the behavior with Javascript for() loops where, without a closure, only the last value is acted upon. My output from the console is as follows:

appending 1784
appending 4057
4057
4057

See... it's telling me it's appending unique busses to my matches list, but when I iterate over the matches list, its only giving me one bus.

Another snippet that tells me something's funky with the second loop:

print 'Matches', matches
    for bus in matches:
        print bus.get('id')
        # Matches [<busutils.Bus instance at 0xb6f92b8c>, <busutils.Bus instance at 0xb6f92d0c>]
        # 4057
        # 4057

The output of the list is showing me different hashes (...right?) of the objects in the list, hence saying they're two different objects, and thus have different data, but the loop isn't playing nicely.

Obviously I'm just getting into python, but have experience in Java, Javascript, PHP, etc, so I'm not sure what I'm missing in these simple loops.

Thanks!

解决方案

It's because of your use of class variables on the Bus class. Make them instance variables (created in __init__).

这篇关于Python循环两次附加同一对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆