我正在通过“使用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'的数据类型是一个整数 –