我正在通過「使用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值中?
基本上,這個:'colWidths [i]''我'不是一個索引。 –
'我'是一個列表。 'some_list [another_list]'沒有任何意義 –
當你在alist中使用'for i時,'i'的數據類型是一個列表,而不是一個整數。 Python會自動爲for語句分配數據類型。如果你希望我是一個整數,你需要重寫你的for循環,所以'i'的數據類型是一個整數 –