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

标签 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))
       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/

相关文章:

java - 将 python 转换为 java float 与 double

python - 列出目录 python OSX

c++ - pyQT slot decorator 什么是 C++ 等价物

python - 如何在 Python 中对号码列表进行排序?

java - 如何定位并打印数组中最大值的索引?

Javascript - 循环访问有效 URL 的数组

python - 将 Snowflake 表数据公开为 REST API

Python-检查它在列表中的位置

r - 将数据框和列表连接到包含列表列的数据框中

r - 帮我用 "apply"函数替换 for 循环