Python 3.6.2—查找子列表中最长字符串的长度,并将该值存储在现有列表中

Python 3.6.2—查找子列表中最长字符串的长度,并将该值存储在现有列表中,python,list,for-loop,Python,List,For Loop,我正在完成“用Python自动化无聊的东西”。其中一个项目希望我: a) 创建一个列表以存储每个子列表中最长字符串的长度colWidths b) 查找tableData列表中每个子列表中最长字符串的所述长度 c) 将长度存储回colWidths 这是我的密码: def printTable(alist): colWidths = [0] * len(alist) for i in alist: colWidths[i] = len(max(i, key=len))

我正在完成“用Python自动化无聊的东西”。其中一个项目希望我:

a) 创建一个列表以存储每个子列表中最长字符串的长度colWidths

b) 查找tableData列表中每个子列表中最长字符串的所述长度

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值中?

A
for..in
循环在每次迭代中逐个使用存储在每个索引中的项。在本例中,您试图用另一个列表索引一个列表,因为
alist
是一个二维列表。你要做的是对范围内的i(len(alist))执行
这样你就可以用数字来索引
colWidths
,而不是一个实际的列表,这是无效的。

基本上,这是:
colWidths[i]
i
不是一个索引。
i
是一个列表
some_list[另一个列表]
并不意味着什么当您在列表中为i使用
时,
i
的数据类型是列表,而不是整数。Python会自动为语句分配数据类型。如果希望i为整数,则需要重写for循环,以便
i
的数据类型为integer@DeniseMoran更具体地说,变量根本不是用Python键入的。PythonforLoops只会吐出迭代器中下一个对象的任何类型。