我正在参加Udacity编程课程并且已经在同一个问题上待了一个星期。我终于认为我已接近正确,但我没有得到最后的反对意见。这是我的代码:
def process_file(f):
# This is example of the datastructure you should return
# Each item in the list should be a dictionary containing all the relevant data
# Note - year, month, and the flight data should be integers
# You should skip the rows that contain the TOTAL data for a year
# data = [{"courier": "FL",
# "airport": "ATL",
# "year": 2012,
# "month": 12,
# "flights": {"domestic": 100,
# "international": 100}
# },
# {"courier": "..."}
# ]
data = []
info = {}
info["courier"], info["airport"] = f[:6].split("-")
with open("{}/{}".format(datadir, f), "r") as html:
soup = BeautifulSoup(html)
car = str(html)[17:19]
airp = str(html)[20:23]
mydict = {}
x = 0
table = soup.find("table", {"class": "dataTDRight"})
rows = table.find_all('tr')
for row in rows:
cells = row.find_all('td')
year = cells[0].get_text()
year = (year.encode('ascii'))
Month = cells[1].get_text()
Month = (Month.encode('ascii'))
domestic = cells[2].get_text()
domestic = (domestic.encode('ascii'))
international = cells[3].get_text()
international = (international.encode('ascii'))
if Month != "Month" and Month != "TOTAL":
Month = int(Month)
year = int(year)
domestic = int(domestic.replace(',', ''))
international = int(international.replace(',', ''))
mydict['courier'] = car
mydict['airport'] = airp
mydict['year'] = year
mydict['month'] = Month
mydict['flights'] = (domestic, international)
data.append(mydict.copy())
#print type(domestic)
#print mydict
print data
return data
def test():
print "Running a simple test..."
open_zip(datadir)
files = process_all(datadir)
data = []
for f in files:
data += process_file(f)
assert len(data) == 399
for entry in data[:3]:
assert type(entry["year"]) == int
assert type(entry["month"]) == int
assert type(entry["flights"]["domestic"]) == int
assert len(entry["airport"]) == 3
assert len(entry["courier"]) == 2
assert data[-1]["airport"] == "ATL"
assert data[-1]["flights"] == {'international': 108289, 'domestic': 701425}
print "... success!"
我得到的错误信息是:
Traceback (most recent call last):
File "vm_main.py", line 33, in <module>
import main
File "/tmp/vmuser_elbzlfkcpw/main.py", line 2, in <module>
import studentMain
File "/tmp/vmuser_elbzlfkcpw/studentMain.py", line 2, in <module>
process.test()
File "/tmp/vmuser_elbzlfkcpw/process.py", line 114, in test
assert type(entry["flights"]["domestic"]) == int
TypeError: tuple indices must be integers, not str
我是初学者,我检查了domestic
和international
的类型,它们都是int。
有人可以告诉我在哪里可以查看或我做错了吗?
答案 0 :(得分:1)
你在这里创建了一个元组:
mydict['flights'] = (domestic, international)
所以mydict['flights']
是一个元组。但是你试着把它当作字典来对待:
assert type(entry["flights"]["domestic"]) == int
这不起作用;你需要在这里使用整数索引:
assert type(entry["flights"][0]) == int
或者更好的是,使用isinstance()
来测试类型:
assert isinstance(entry["flights"][0], int)
答案 1 :(得分:1)
您可以在此处将数据mydict['flights']
指定为tuple
。
def process_file(f):
# Omitted code...
mydict['flights'] = (domestic, international)
您的错误来自非法访问该数据类型。您正尝试按照分配中使用的变量名称访问该tuple
的第一项:
assert type(entry["flights"]["domestic"]) == int
您需要通过整数索引访问您的数据:
assert type(entry["flights"][0]) == int
或者您需要将作业更改为:
mydict['flights'] = {"domestic":domestic, "international":international}
tuple
是不可变的数据类型,由整数索引。您尝试的访问类型是典型的dict
ionary,其中索引可以是任何类型。