我正在研究“用 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 值中?
最佳答案
for..in
循环每次迭代都会使用存储在每个索引中的项目。在这种情况下,您尝试用另一个列表索引一个列表,因为 alist
是一个二维列表。您想要做的是 for i in range(len(alist)):
这样您就可以使用数字来索引 colWidths
而不是实际的列表,这是无效的.
关于Python 3.6.2 - 查找子列表中最长字符串的长度并将该值存储在现有列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46800536/