我试图确定字典中是否存在特定的键和值对;但是,如果使用contains或has key方法,它只检查键。我需要它检查键和具体值。一些背景: 我们总共有4本字典:一本是a、B、CompareList和ChangeList。初始化A之后,我将A的内容放入CompareList(我将直接比较它们;但是A和B是双哈希表。我已经尝试过这里所有的方法,但是没有一种对我有效)。因此,一旦我们将A放入CompareList,我将它与B中的ObjectAttributes字典进行比较,看看是否有任何变化。例如,B可以有键,值对shape:circle和fill:no。如果CompareList有shape:circle和fill:yes,那么我只希望fill:yes是变更列表。问题在于“if attributes.getName()不在self.CompareList:”行中。这是代码;我在Python2.7.8上运行它。提前感谢您的帮助!!
class ObjectSemanticNetwork:
def __init__(self):
self.ObjectNames = {}
self.ObjectAttributes = {}
def setName(self, name):
self.ObjectNames[name] = self.ObjectAttributes
def setData(self, name, attribute):
self.ObjectAttributes[name] = attribute
def checkData(self, key):
print(key)
for key, value in self.ObjectAttributes.iteritems():
print(key)
print(value)
print("\n")
class Agent:
(self):
self.CompareList = {}
self.ChangeListAB = {}
self.ChangeListCD = {}
def addToCompareList(self, name, value):
self.CompareList[name] = value
def addToChangeListAB(self, name, value):
self.ChangeListAB[name] = value
def addToChangeListCD(self, name, value):
self.ChangeListCD[name] = value
def CheckList(self, List, ListName):
print '-------------------------',ListName,'--------------------------------'
for key, value in List.iteritems():
print(key)
print(value)
def Solve(self,problem):
OSNAB = ObjectSemanticNetwork()
for object in problem.getFigures().get("A").getObjects():
for attributes in object.getAttributes():
self.addToCompareList(attributes.getName(), attributes.getValue())
OSNAB.ObjectNames["A"] = OSNAB.setData(attributes.getName(), attributes.getValue())
#OSNAB.checkData("A")
self.CheckList(self.CompareList,"CompareList")
for object in problem.getFigures().get("B").getObjects():
for attributes in object.getAttributes():
if attributes.getName() not in self.CompareList:
self.addToChangeListAB(attributes.getName(), attributes.getValue())
OSNAB.ObjectNames["B"] = OSNAB.setData(attributes.getName(), attributes.getValue())
# OSNAB.checkData("B")
self.CheckList(self.ChangeListAB,"ChangeList")
OSNCD = ObjectSemanticNetwork()
for object in problem.getFigures().get("C").getObjects():
for attributes in object.getAttributes():
OSNCD.ObjectNames["C"] = OSNCD.setData(attributes.getName(), attributes.getValue())
# OSNCD.checkData("C")
for object in problem.getFigures().get("1").getObjects():
for attributes in object.getAttributes():
OSNCD.ObjectNames["D"] = OSNCD.setData(attributes.getName(), attributes.getValue())
# OSNCD.checkData("D")
return "6"
这个功能怎么样:
如果您使用的是python提供的另一种类型的字典(很抱歉,我无法从您的文章中理解您是否使用它),那么请告诉我,我将尝试为您提供另一种解决方案
为什么不这样做:
使用
或(仅在Python3中)
在Python 3中,
d.items()
返回一个Dictionary view object,它支持快速的成员资格测试。在Python 2中,d.items()
返回一个列表,该列表创建速度慢,测试成员身份也慢。Python 2.7是一个特殊情况,在这里您可以使用d.viewitems()
,并获得与Python 3中的d.items()
相同的结果。编辑:在注释中,您表示出于性能原因,您更喜欢
checkKeyValuePairExistence
而不是key in d and d[key] == value
。下面是一些计时,显示checkKeyValuePairExistence
总是慢一些(在我的系统上,当键值对存在时大约慢2倍,当键值对不存在时则慢16倍)。我还测试了越来越大的字典,发现时间变化不大。相关问题 更多 >
编程相关推荐