2015-04-07 33 views
0

我正在參加一個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類型。

有人可以告訴我在哪裏可以擡頭或我做錯了什麼?

+9

你可以發佈完整的回溯。 –

+6

你收到的* full *錯誤信息是什麼?回溯告訴我們*發生錯誤的地方,而不僅僅是發生錯誤。 –

+0

我們需要完整的回溯,它告訴我們錯誤發生在哪一行。 (一旦你知道了,你也可以在錯誤發生之前添加一條打印語句,這樣我們可以看到有問題的命令是什麼) – smci

回答

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) 
+0

好吧非常感謝你的幫助!!! mydict ['航班'] = {「國內」:國內,「國際」:國際}我不知道在字典中我可以有這樣一個結構非常坦率,我認爲我可以只有鍵/值(s)對...而不是用字符串來描述它,謝謝大家很多,我會繼續學習編程:) –

+0

@StephanKetterer關於從我的答案中的位,你可以使用任何可哈希的類型,所以:字符串,整數,浮點數等[見本術語表中的哈希值)](https://docs.python.org/2/glossary.html) –

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 s爲它們由整數索引的不可變的數據類型。您嘗試訪問的類型通常是dictionary,其中索引可以是任何類型。

相關問題