0

我在使用字典时遇到了一些奇怪的问题,我正在尝试从字典中迭代对以传递给另一个函数。尽管出于某种原因,迭代器的循环总是返回空值。

这是代码:

  def LinktoCentral(self, linkmethod):
    if linkmethod == 'sim':
        linkworker = Linker.SimilarityLinker()
        matchlist = []

        for k,v in self.ToBeMatchedTable.iteritems():

            matchlist.append(k, linkworker.GetBestMatch(v, self.CentralDataTable.items()))

现在,如果我在 for 循环上方插入打印行:

matchlist = []
print self.ToBeMatchedTable.items()        
for k,v in self.ToBeMatchedTable.iteritems():

            matchlist.append(k, linkworker.GetBestMatch(v, self.CentralDataTable.items()))

我得到了应该在字典中打印的数据。字典的值是列表对象。我在 for 循环上方打印时从字典中获得的示例元组:

>>> (1, ['AARP/United Health Care', '8002277789', 'PO Box 740819', 'Atlanta', 'GA','30374-0819', 'Paper', '3676'])

但是,for 循环为 linkworker.GetBestMatch 方法提供了空列表。如果我在 for 循环正下方放置一条打印线,我会得到:

代码:

matchlist = []

        for k,v in self.ToBeMatchedTable.iteritems():
            print self.ToBeMatchedTable.items()
            matchlist.append(k, linkworker.GetBestMatch(v, self.CentralDataTable.items()))

            ## Place holder for line to send match list to display window
        return matchlist

第一次迭代的结果:

>>> (0, ['', '', '', '', '', '', '', ''])

我真的不知道发生了什么,执行此循环时没有其他任何事情发生。我犯了什么愚蠢的错误?

4

1 回答 1

1

假设如下:

d = {1: [1,2,3,4,54,6,7,8]}

print d.items()

for k,v in d.iteritems():
    print k, v

Output:
[(1, [1, 2, 3, 4, 54, 6, 7, 8])]
1 [1, 2, 3, 4, 54, 6, 7, 8]

self.ToBeMatchedTable拥有的不仅仅是one pair密钥和价值 通常Python dictionariesunordered,当您尝试访问它时,它会以随机方式工作

在你的情况下:

有一个像这样的键值对(0, ['', '', '', '', '', '', '', '']),所以第二次,你得到了这个!

您的代码中似乎有问题:

matchlist.append(k, linkworker.GetBestMatch(v, self.CentralDataTable.items()))

我模拟了类似于上述行的东西

>>> l = []
>>> 
>>> l.append(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: append() takes exactly one argument (2 given)

尝试评论或修改您的matchlist.append(...)行:

matchlist.append((k, linkworker.GetBestMatch(v, self.CentralDataTable.items())))

于 2013-10-27T10:12:17.293 回答