[英]Accessing a variable outside of a for loop in Python if global doesn't work?
我正在尝试在字典中的两个数据集之间找到相似的记录,以进行进一步的比较。
我已通过一条打印语句确认它正在查找匹配的数据集(因此,最终if语句之前的所有代码均有效)。 但是由于某种原因,它没有设置matchingSet2Record
。 即使找到匹配项,这也会导致最终的if语句始终运行。 将变量声明为全局变量作用域不起作用。 是什么导致这种情况发生? 如何将第一个mathingSet2Record
设置为for循环中的发现记录?
我使用此代码具有唯一的问题是,即使matchingSet2Record
设置为找到的记录正确的,它仍然具有的价值None
试图将它在最后的if语句比较时。 比较逻辑功能正常。
我有以下功能:
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"
每个答案/评论的更新代码(仍然显示相同的问题)
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"
“数据”是词典的字典。 代码的那部分工作正常。 当我在将其设置为匹配记录的for循环内打印matchingSet2Record时,它表明变量已正确设置,但是当我在for循环外执行此操作时,它显示的值为None。 这就是我正在用这段代码探索的问题。 该问题与查找匹配记录的代码无关。
请勿在此处使用global
关键字。 您实际上要设置局部变量matchingSet2Record
,而不是全局变量。
您拥有的代码实际上是在全局范围内设置变量的值,这实际上使局部变量matchingSet2Record
保持不变。 这会导致if语句的条件始终评估为True
因为matchingSet2Record
的值从未更新为非None
。
这不是最终答案,但要发表评论实在太多了。
我试图用实际的data
来重现您的问题。 但是您的代码确实有效。 必须有
data
(例如,在一个可迭代对象上进行两次迭代时,我已经看到了奇怪的效果,因为可迭代对象已经“被消耗”了) 这有效:
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")
else:
print("Found")
if __name__ == '__main__':
data = dict(Set1=[dict(Field1='value1')], Set2=[dict(Field2='value1')])
processFile(data)
打印Found
编辑 :
如果您正在学习python,那么可以像上面这样写上面的代码:
data = dict(Set1=[dict(Field1='value1')], Set2=[dict(Field2='value1 ')])
for value1 in [v['Field1'].strip() for v in data['Set1']]:
try:
matchingSet2Record = (v for v in data['Set2'] if v['Field2'].strip() == value1).next()
print("found {}".format(matchingSet2Record))
except StopIteration:
print('Missing')
最后一行生成一个生成器:( (. for . in .)
创建一个生成器,然后next()
使其生成,直到找到第一个匹配项为止。 如果您错过了,将遇到StopIteration
异常。
或者,或者,如果您只是想找出Set1和Set2之间是否存在重叠,则可以执行以下操作:
data = dict(Set1=[dict(Field1='value1')], Set2=[dict(Field2='value1')])
field1 = [a['Field1'].strip() for a in data['Set1']]
field2 = [a['Field2'].strip() for a in data['Set2']]
if not set(field1).isdisjoint(field2):
print('there is at least 1 common element between Set1 and Set2')
请参阅此答案以了解有关isdisjoint
部分的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.