두 사전 사전의 인덱스 값을 비교하려고합니다. 이를 위해 중첩 된 for 루프를 사용하고 있습니다. 루프가 올바르게 반복되는 동안에는 firstDataSetNumber
이 중첩 된 for 루프 (두 번째 print 문으로 표시) 내부를 반복하지 않는 문제가 있습니다. 첫 번째 print 문은 for 루프가 올바르게 반복되고 있음을 보여줍니다. 중첩 된 for 루프 내의 두 번째 firstDataSetNumber
에서 인쇄 된 값을 변경하지 못하게하는 원인은 무엇입니까? 첫 번째 print 문의 값이 실제로 반복적으로 반복되고 있음을 보여줍니다.중첩 for 루프에서 상위 for 루프에 액세스 할 수 없습니다.
def processCommandCenterFile(data):
firstDataSet = data["FirstDataSet"]
secondDataSet = data["SecondDataSet"]
# Go through every First Data Set Record
for firstDataSetRecord in firstDataSet:
firstDataSetNumber = firstDataSetRecord["KeyOne"].strip()
matchingSecondDataSetRecord = None
print(firstDataSetNumber) # Always iterates properly throughout the application
# Find the Second Data Set record with the KeyTwo number
for secondDataSetRecord in secondDataSet:
print(firstDataSetNumber) # Never iterates past the first value
if secondDataSetRecord["KeyTwo"].strip() == firstDataSetNumber:
matchingSecondDataSetRecord = secondDataSetRecord
data = {
"FirstDataSet": CsvToDictionary("first_data_set.csv"),
"SecondDataSet": CsvToDictionary("second_data_set.csv")
}
processCommandCenterFile(data)
두 출력의 출력이 동일 할 것으로 예상됩니다. 그러나 그것을 실행할 때 첫 번째 print 문은 인덱스의 각 항목이지만 두 번째 print 문에서 가져온 데이터는 목록의 첫 번째 항목에 붙어 있습니다.
FirstDataSet 및 SecondDataSet 키에는 CSV를로드하고 CSV의 헤더를 키로 사용하여 사전으로 변환하는 다음 함수의 출력을 저장합니다. Heres는
import csv
def CsvToDictionary(path):
file = open(path, 'r')
rawCsvArray = csv.reader(file, delimiter=',', quotechar='|')
headers = rawCsvArray.next()
dataDictionary = csv.DictReader(file, fieldnames=headers)
return dataDictionary
FirstDataSet
KeyOne
143739629
143739629
143750196
143750196
143739646
143739646
143739661
143739661
143739718
을 만드는 데 사용됩니다 그리고 사용 년대 CSV 설정 번호가 보이는 SecondDataSet
KeyTwo
143739629
143739629
143750196
143750196
143739646
143739646
143739661
143739661
143739718
'firstDataSet'과'secondDataSet'에 무엇이 포함되어 있는지와 원하는 결과를 말할 수 있다면 더 도움이 될 것입니다.더 나은 해결책이있을 수도 있습니다. –
귀하의 질문을 보여주는 가능한 최소 ** 완성 ** 프로그램으로 프로그램을 축소하십시오. 프로그램의 실제 및 예상 출력을 포함하십시오. 자세한 내용은 [mcve]를 참조하십시오. –
예상되는 출력은 무엇입니까? 코드의 주석에서 코드가 제대로 작동하는 것 같습니다. – MFisherKDX