0

对不起,我又回来了。这次我试图获取每个停车场的注册数量并添加了以下代码:

data_dict = {}
dict_list = []
def createNameDict(filename):
  path = "C:\Users\user\Desktop"
  basename = "ParkingData_Part2.txt"
  filename = path + "//" + basename
  file = open(filename)
  contents = file.read()
  print contents,"\n"


  data_list = [lines.split(",") for lines in contents.split("\n")]



  for line in data_list:
    regNumber = line[0]
    name = line[1]
    phoneExtn = line[2]
    carpark = line[3]
    details = (name,phoneExtn,carpark)

    data_dict[regNumber] = details
  print data_dict,"\n"
  print data_dict.items(),"\n"

def getDetails(regNumber):
  try:
    print data_dict[regNumber]
  except:
    print regNumber, " not in dictionary"
    return
def addRegistration(regNumber, details):
  if regNumber not in data_dict:
    data_dict[regNumber] = details

    print regNumber, ":", details, "Registration details added"
  else:
    print regNumber, "Key Already exist, \n"


  return data_dict
def registrationsPerCarpark(carpark):

  for regNumber, details in data_dict:        
    return [key for key, value in data_dict.iteritems() if value == details][0]
  #for carpark in data_dict.values():
   # print sum(int(carpark))
    #return

但是这些值没有加起来,因为它们不是数字。我在谷歌上搜索了很多,但没有得到任何关于这方面的信息。我的代码的输出是这样的:

====== Loading Progam =======
>>> createNameDict("C:\Users\user\Desktop//ParkingData_Part2.txt")
EDF768, Bill Meyer, 2456, Vet_Parking
TY5678, Jane Miller, 8987, AgHort_Parking
GEF123, Jill Black, 3456, Creche_Parking
ABC234, Fred Greenside, 2345, AgHort_Parking
GH7682, Clara Hill, 7689, AgHort_Parking
JU9807, Jacky Blair, 7867, Vet_Parking
KLOI98, Martha Miller, 4563, Vet_Parking
ADF645, Cloe Freckle, 6789, Vet_Parking
DF7800, Jacko Frizzle, 4532, Creche_Parking
WER546, Olga Grey, 9898, Creche_Parking
HUY768, Wilbur Matty, 8912, Creche_Parking 

{'HUY768': (' Wilbur Matty', ' 8912', ' Creche_Parking'), 'GH7682': (' Clara Hill', ' 7689', ' AgHort_Parking'), 'GEF123': (' Jill Black', ' 3456', ' Creche_Parking'), 'WER546': (' Olga Grey', ' 9898', ' Creche_Parking'), 'TY5678': (' Jane Miller', ' 8987', ' AgHort_Parking'), 'ABC234': (' Fred Greenside', ' 2345', ' AgHort_Parking'), 'KLOI98': (' Martha Miller', ' 4563', ' Vet_Parking'), 'EDF768': (' Bill Meyer', ' 2456', ' Vet_Parking'), 'JU9807': (' Jacky Blair', ' 7867', ' Vet_Parking'), 'DF7800': (' Jacko Frizzle', ' 4532', ' Creche_Parking'), 'ADF645': (' Cloe Freckle', ' 6789', ' Vet_Parking')} 

[('HUY768', (' Wilbur Matty', ' 8912', ' Creche_Parking')), ('GH7682', (' Clara Hill', ' 7689', ' AgHort_Parking')), ('GEF123', (' Jill Black', ' 3456', ' Creche_Parking')), ('WER546', (' Olga Grey', ' 9898', ' Creche_Parking')), ('TY5678', (' Jane Miller', ' 8987', ' AgHort_Parking')), ('ABC234', (' Fred Greenside', ' 2345', ' AgHort_Parking')), ('KLOI98', (' Martha Miller', ' 4563', ' Vet_Parking')), ('EDF768', (' Bill Meyer', ' 2456', ' Vet_Parking')), ('JU9807', (' Jacky Blair', ' 7867', ' Vet_Parking')), ('DF7800', (' Jacko Frizzle', ' 4532', ' Creche_Parking')), ('ADF645', (' Cloe Freckle', ' 6789', ' Vet_Parking'))] 

>>> registrationsPerCarpark("AgHort_Parking")
The error was:__getitem__
Attribute not found.
You are trying to access a part of the object that doesn't exist.
Please check line 48 of C:\Users\user\Desktop\159171\assignment2_part2
4

3 回答 3

0

这是另一种更紧凑的方法。

import csv
from collections import defaultdict

rows = defaultdict(set)

with open('in.csv') as f:
  lines = csv.reader(f)
  for line in lines:
      rows[line[3].strip()].add((line[0],line[1],line[2]))

for key in rows:
   print 'Total number of cars for %s is %s' % (key,len(rows[key]))

结果是:

The total number of cars for Creche_Parking is 4
The total number of cars for AgHort_Parking is 3
The total number of cars for Vet_Parking is 4
于 2012-05-15T14:14:01.973 回答
0

该行for regNumber, details in data_dict是错误的,您不能以这种方式迭代 dict 。您可能的意思是for regNumber, details in data_dict.items()(或iteritems(),但这将是 Python 2 特定的)。

如果我对任务的理解正确,函数体应该如下所示:

def registrationsPerCarpark(carpark):

    return sum(value[2]=carpark for value in data_dict.values())

请注意值中的空格:例如,您应该寻找' AgHort_Parking',而不是'AgHort_Parking'。为了解决这个问题,改变createNameDict

carpark = line[3].strip()

等等。此外,createNameDict内存效率低,因为它一次将文件内容加载到内存中。要减少内存使用量,请执行以下操作:

data_list = []
with open(filename) as infile:
  data_list = [lines.split(",") for lines in contents.split("\n")]
  for line in infile:
        data_list.append(line.split(','))
        print line
于 2012-05-15T13:20:10.327 回答
0
def registrationsPerCarpark(carpark):
    for regNumber, details in data_dict:        
        return [key for key, value in data_dict.iteritems() if value == details][0]

您的for循环将不起作用,因为in dictionary迭代的构造只返回key,而不是(key, value)对。其次,您从不使用carpark变量。第三,它是无关紧要的,因为您之后在 return 语句中循环遍历它,尽管您对它的使用没有意义。可以假设您只需要计算特定停车场的汽车数量吗?

于 2012-05-15T13:22:33.650 回答