python - 返回列表中最长单词的 len

标签 python list python-2.7 maxlength

<分区>

你好,我正在尝试制作一个 python 程序,它将返回列表中最长单词的长度,但它对我来说效果不佳。

代码如下:

def find_longest_word():
   list1 = ['a','aa','aaa','aaaa','aaaaa','aaaaaa','aaaaaaa','aaaaaaaa',]
   max1 = ''
   for x in range (0, len(list1)):
      if (len(max1) < len(list1[x]) ):
          max1 = list1[x]
   return max1    


def main():
    m = find_longest_word()
    print len(m)

最佳答案

实际上,您的问题很简单:您忘记在脚本末尾调用 main 函数:

main()

当您这样做时,它会打印 8,就像它应该的那样。


但是,如果使用 max,您可以更轻松地完成此任务。及其 key function :

>>> list1 = ['a','aa','aaa','aaaa','aaaaa','aaaaaa','aaaaaaa','aaaaaaaa',]
>>> max(list1, key=len)
'aaaaaaaa'
>>> len(max(list1, key=len))
8
>>>

编辑:

虽然我的上述解决方案工作正常,但我想提供一个我刚刚想到的更短的解决方案:

>>> list1 = ['a','aa','aaa','aaaa','aaaaa','aaaaaa','aaaaaaa','aaaaaaaa',]
>>> max(map(len, list1))
8
>>>

此解决方案使用 map 而不是关键函数.

关于python - 返回列表中最长单词的 len,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21467762/

相关文章:

python - 用于约束参数的卡方检验

python - 连接具有相同 id 的 pandas DataFrame 行

python - tkinter 滚动条折叠它所在的 Canvas

c# - 具有多个索引的列表

python - Django-piston 的读取响应时间很长

python-2.7 - TensorFlow,类型错误: random_normal() got an unexpected keyword argument 'partition_info'

python - 比较/映射不同数据帧中的不同系列

python - 如何使用 Python 锁定 Azure 资源组中的所有资源

c# - ASP GridView 列表

python - 使用给定值创建给定长度的列表 - 将直方图转换为值列表