더 많은 비교를 할 사전에 두 데이터 세트 사이에 유사한 레코드를 찾으려고합니다.전역 변수가 작동하지 않는 경우 Python에서 for 루프 외부의 변수에 액세스합니까?
print 문을 사용하여 일치하는 데이터 세트를 찾았습니다 (최종 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"
업데이트 코드 (여전히 같은 문제를 전시)
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"
"데이터"사전의 사전은 다음과 같습니다
나는 다음과 같은 기능을 가지고있다. 코드 부분이 제대로 작동하고 있습니다. matchSet2Record를 for 루프 내에서 인쇄 할 때 해당 레코드를 일치하는 레코드로 설정하면 변수가 제대로 설정되었음을 알 수 있습니다. 그러나 for 루프 외부에서 수행하면 None 값이 표시됩니다. 이것이이 코드로 탐구하는 문제입니다. 문제는 일치하는 레코드를 찾는 코드와 관련이 없습니다.
만약 함수의 특정 지점에서 멈추길 원한다면 그것은'return' 문을위한 것입니다. –
그것이 설명되는 문제는 아닙니다. 최종 for 문에서 액세스 할 수 있도록 첫 번째 for..in 루프에서 발견 된 레코드에 None으로 선언 된 matchingSet2Record의 값을 변경할 수 있기를 원합니다. – Kirkland
당신이 게시 한 코드는'globalSetupRecord'가 global로 선언되기 전에'SyntaxError'를 발생시킵니다. 문제가 무엇인지 그리고 당신의 코드가 무효라는 것을 분명히 이해하지 못하기 때문에 질문을 명확히하십시오. –