如果全局不起作用,则在Python中的for循环之外访问变量? [英] Accessing a variable outside of a for loop in Python if global doesn't work?

查看:150
本文介绍了如果全局不起作用,则在Python中的for循环之外访问变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在字典中的两个数据集之间找到相似的记录,以进行进一步的比较.

I'm trying to find a similar record between two data sets in a dictionary with which to do further comparisons.

我已通过一条打印语句确认它正在查找匹配的数据集(因此,最终if语句之前的所有代码均有效).但是由于某种原因,它没有设置matchingSet2Record.这将导致最终的if语句即使找到匹配项也始终运行.将变量声明为全局变量作用域不起作用.是什么原因导致这种情况发生?如何在for循环中将第一个mathingSet2Record设置为发现的记录?

I've confirmed with a print statement that it is finding a matching data set (so all of the code before the final if statement is working). However it is not setting the matchingSet2Record for some reason. This causes the final if statement to always run even though it is finding a match. Declaring the variable as being in the global variable scope does not work. What is causing this to happen? How do I set the first mathingSet2Record to the discovered record in the for loop?

此代码的唯一问题是,即使将matchingSet2Record正确设置为找到的记录,当尝试在最终的if语句中进行比较时,它仍然具有None的值.比较逻辑运行正常.

The only problem I'm having with this code is that even though matchingSet2Record is set to the found record properly, it still has a value of None when trying to compare it in the final if statement. The comparison logic is functioning properly.

我具有以下功能:

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"

每个答案/评论的更新代码(仍然显示相同的问题)

Updated code per answers/comments (still exhibiting the same issue)

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.这就是我正在用这段代码探索的问题.问题与找到匹配记录的代码无关.

"data" is a dictionary of dictionaries. That portion of the code is working properly. When I print matchingSet2Record within the for loop that set's it to the matching record it shows that the variable was set properly, however when I do it outside of the for loop it shows a value of None. That is the problem that I'm exploring with this code. The problem does not have anything to do with the code that finds a matching record.

推荐答案

这不是最终的答案,但是太多了,不能发表评论.

This is not a final answer but it's just too much to put into a comment.

我试图用data的实际格来重现您的问题.但是您的代码确实有效.要么需要

I tried to reproduce your problem with an actual dict of data. But your code really works. There needs to either be

  • data的一些特殊之处(例如,在一个可迭代对象上迭代两次时,我已经看到了奇怪的效果,因为可迭代对象已经被消耗"了)
  • 或者它实际上不匹配,因为您在Field1和Field2的两个字符串之间有一些看不见的差异.
  • some pecularities of data (I've seen strange effects when e.g. iterating twice over an iterable, because the iterable was already "consumed")
  • or it really does not match, because you have some invisible differences between the two strings in Field1 and Field2.

这有效:

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,则可以将上面的代码写得更短:

If you're into learning python then you can write the above shorter like this:

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异常.

The last line does a generator: (. for . in .) creates a generator and next() makes it generate until it finds the first match. If you get a miss, you'll hit the StopIteration exception.

或者,或者,如果您只是想找出如果,则Set1和Set2之间存在重叠,您可以这样做:

Or, alternatively, if you're just into finding out if there are overlaps between the Set1 and Set2 you could do:

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部分.

See this answer to read more about the isdisjoint part.

这篇关于如果全局不起作用,则在Python中的for循环之外访问变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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