gpt4 book ai didi

python - 如何在嵌套列表中获取最大字符串长度

转载 作者:太空狗 更新时间:2023-10-30 02:56:47 24 4
gpt4 key购买 nike

它们是我之前帖子的后续问题(从列表列表中重新打印表格)

我正在尝试获取以下嵌套列表的字符串最大值:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]

for i in tableData:
print(len(max(i)))

这给了我 7、5、5。但是“樱桃”是 8

我在这里错过了什么?谢谢。

最佳答案

您已经完成了最大单词的长度。这给出了错误的答案,因为单词是有序的 lexicographically :

>>> 'oranges' > 'cherries'
True

您可能想要的是单词的最大长度:

max(len(word) for word in i)

或等效地:

len(max(i, key=len))

关于python - 如何在嵌套列表中获取最大字符串长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39373620/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com