2017-10-17 55 views
1

我正在通過「使用Python自動化煩人的東西」。其中一個項目希望我:Python 3.6.2 - 查找子列表中最長字符串的長度並將該值存儲在現有列表中

a)創建一個列表來存儲每個子列表中最長字符串的長度colWidths。

二)發現的最長的字符串表示的長度在資料表列表中的每個子表

C)存儲長度回colWidths

這裏是我的代碼:

def printTable(alist): 
    colWidths = [0] * len(alist) 
    for i in alist: 
     colWidths[i] = len(max(i, key=len)) 
     print(colWidths(i)) 


tableData = [['apples','oranges','cherries', 'banana'], 
      ['Alice', 'Bob', 'Carol', 'David'], 
      ['dogs', 'cats', 'moose', 'goose']] 
printTable(tableData) 

#TODO: Make each list into a column that uses rjust(n) to justify all of 
#the strings to the right n characters 

每當我跑這個代碼,我得到這個錯誤第4行:

TypeError: list indices must be integers or slices, not list 

爲什麼可以'我使用colWidths [i]來獲取len(max(i,key-len))的結果並將其存儲在相應的colWidths值中?

+0

基本上,這個:'colWidths [i]''我'不是一個索引。 –

+0

'我'是一個列表。 'some_list [another_list]'沒有任何意義 –

+0

當你在alist中使用'for i時,'i'的數據類型是一個列表,而不是一個整數。 Python會自動爲for語句分配數據類型。如果你希望我是一個整數,你需要重寫你的for循環,所以'i'的數據類型是一個整數 –

回答

1

A for..in循環每次迭代使用存儲在每個索引中的項目一個接一個。在這種情況下,您試圖使用另一個列表來索引列表,因爲alist是一個二維列表。你想要做的是for i in range(len(alist)):這樣你使用數字來索引colWidths而不是實際列表,這是無效的。

0

i不是合法的整數索引,您不能使用它來訪問列表元素。嘗試聲明一個空列表並附加到它。

colWidths = [] 
for i in alist: 
    colWidths.append(len(max(i, key=len))) 

此外,print(colWidths(i))是無效的,因爲list是不可調用的。使用[..]方括號來索引。

相關問題