2017-10-17 46 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是不可调用的。使用[..]方括号来索引。

相关问题