我试图比较两个字典数组之间的索引值。为此,我使用了嵌套for循环。当循环正确地迭代时,有一个问题,firstDataSetNumber
没有在嵌套for循环内迭代(由第二个print语句指示)。第一个print语句显示for循环正在正确地迭代。是什么原因导致嵌套for循环中从第二个firstDataSetNumber
打印的值永远不会更改,即使第一个print语句中的值表明它确实在正确迭代?你知道吗
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语句是索引中的每一项,而第二个print语句中的数据则被卡在列表中的第一项上。你知道吗
FirstDataSet和SecondDataSet键存储以下函数的输出,该函数加载CSV并将其转换为字典,其中CSV的头作为键。你知道吗
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
的CSV
KeyOne
143739629
143739629
143750196
143750196
143739646
143739646
143739661
143739661
143739718
然后是用来制作SecondDataSet
的CSV
KeyTwo
143739629
143739629
143750196
143750196
143739646
143739646
143739661
143739661
143739718
我解决了这个问题(多亏了Blckknght),但是将输出转换为csv.DictReader文件像这样的名单:
柯克兰回答了这个问题的实际解决办法。这里有一点背景,如果有人在这里结束。你知道吗
问题是
csv.DictReader()
产生了一个类型为DictReader
的实例,根据the docs,“它的操作就像一个普通的读取器一样。”这意味着从
DictReader
读取值会耗尽实例的内容。在第一轮内环之后,
secondDataSet
中什么都没有了。在以后的迭代中,内部循环没有任何元素可以迭代。你知道吗这可以通过向
print
语句添加标志来验证:输出:
正如Kirkland所指出的,最好的选择是将
DictReader
转换为dict列表,例如(或者只使用熊猫)
第一个数据集编号看起来是在第二个数据集编号开始之前声明的。那么第二组中的每个人都应该看第一个数据集
相关问题 更多 >
编程相关推荐