【发布时间】:2017-12-15 20:39:51
【问题描述】:
我正在尝试在字典中的两个数据集之间找到相似的记录,以便进行进一步比较。
我已通过打印语句确认它正在寻找匹配的数据集(因此最终 if 语句之前的所有代码都在工作)。但是由于某种原因,它没有设置matchingSet2Record。这会导致最终的 if 语句始终运行,即使它正在找到匹配项。将变量声明为在全局变量范围内不起作用。是什么导致这种情况发生?如何将第一个 mathingSet2Record 设置为 for 循环中发现的记录?
我在这段代码中遇到的唯一问题是,即使 matchingSet2Record 已正确设置为找到的记录,但在最后的 if 语句中尝试比较它时,它的值仍然为 None .比较逻辑运行正常。
我有以下功能:
def processFile(data):
# Go through every Record
for set1Record in data["Set1"]:
value1 = set1Record["Field1"].strip()
matchingSet2Record = None
# Find the EnergyIP record with the meter number
for set2Record in data["Set2"]:
if set2Record["Field2"].strip() == value1:
global matchingSet2Record
matchingSet2Record = set2Record
# If there was no matching Set2 record, report it
if matchingSet2Record == None:
print "Missing"
每个答案/cmets 更新的代码(仍然显示相同的问题)
def processFile(data):
# Go through every Record
for set1Record in data["Set1"]:
value1 = set1Record["Field1"].strip()
matchingSet2Record = None
# Find the EnergyIP record with the meter number
for set2Record in data["Set2"]:
if set2Record["Field2"].strip() == value1:
matchingSet2Record = set2Record
# If there was no matching Set2 record, report it
if matchingSet2Record == None:
print "Missing"
"data" 是字典的字典。这部分代码工作正常。当我在 for 循环中打印 matchSet2Record 并将其设置为匹配记录时,它显示该变量已正确设置,但是当我在 for 循环之外执行此操作时,它显示的值为 None。这就是我正在用这段代码探索的问题。该问题与找到匹配记录的代码无关。
【问题讨论】:
-
如果你想让它在函数中的某个点停止,这就是
return语句的用途。 -
这不是所描述的问题。我希望能够将声明为 None 的 matchingSet2Record 的值更改为在第一个 for..in 循环中找到的记录,以便可以在最后的 if 语句中访问它。
-
您发布的代码引发了
SyntaxError,因为matchingSet2Record在声明为全局之前已分配,请澄清您的问题,因为我显然不明白您的问题是什么并且您的代码无效. -
data的类型是什么?是字典吗?还是它的一部分是可迭代的? -
data 是字典的字典。这部分代码工作正常。当我在 for 循环中打印 matchingSet2Record 并将其设置为匹配记录时,它表明变量设置正确,但是当我在 for 循环之外执行它时,它显示的值为 None