构建字典时元组索引必须是整数
Tuple indices must be integers when building a dictionary
我正在参加 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。
任何人都可以告诉我在哪里可以查找或我做错了什么吗?
您在这里创建了一个元组:
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)
在这里,您将数据 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
s 是不可变数据类型,由整数索引。您尝试的访问类型是典型的 dict
ionary,其中索引可以是任何类型。
我正在参加 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。
任何人都可以告诉我在哪里可以查找或我做错了什么吗?
您在这里创建了一个元组:
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)
在这里,您将数据 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
s 是不可变数据类型,由整数索引。您尝试的访问类型是典型的 dict
ionary,其中索引可以是任何类型。