我已经嵌套了DictReader迭代器,但是我注意到for build in building
中的for row in location
在每次迭代后都没有重置import csv
building = csv.DictReader(open('tblBuilding.csv', newline=''), delimiter=',', quotechar='"')
purpose = csv.DictReader(open('tblPurpose.csv', newline=''), delimiter=',', quotechar='"')
room = csv.DictReader(open('tblRoom.csv', newline=''), delimiter=',', quotechar='"')
location = csv.DictReader(open('Locations.csv', newline=''), delimiter=',', quotechar='"')
data, i = {}, 0
for row in location:
result = {}
for build in building:
if row['Build'] == build['BuildingName']:
result['BuildingID'] = build['BuildingID']
,导致它只在第一次迭代后将它与构建中的最后一个对象进行比较。为什么不重置?
{{1}}
答案 0 :(得分:2)
它们不会重置,因为底层文件对象未重置。您可以将文件重新回到开头,但考虑到第一行是标题行,所以也跳过它:
building_file = open('tblBuilding.csv', newline='')
building = csv.DictReader(building_file, delimiter=',', quotechar='"')
for row in location:
result = {}
for build in building:
if row['Build'] == build['BuildingName']:
result['BuildingID'] = build['BuildingID']
building_file.seek(0) # rewind the underlying file object to the start again
next(building) # skip header row
然而,您不应该首先在上嵌套嵌套的CSV文件。在处理位置之前,将建筑信息存储在字典中
with open('tblBuilding.csv', newline='') as building_file:
building = csv.DictReader(building_file, delimiter=',', quotechar='"')
buildings = {b['BuildingName']: b['BuildingID'] for b in building}
buildings
词典现在将BuildingName
映射到BuildingID
值。现在,您可以在O(1)常数时间内查找建筑物,而不必遍历每个位置的所有CSV行 :
for row in location:
result = {}
building_id = buildings.get(row['Build'])
if building_id:
result['BuildingID'] = building_id