在Python列表中显示所有最长的单词

问题描述 投票:0回答:1

我想显示列表中最长的所有单词。我使用过max函数,但是max函数仅返回列表中最大字符串的第一个,即“ have”。如何使它打印出字符串中所有最长的元素?

理想的输出:'具有''变得''良好'获得的输出:'have'

def longestWord(input_str):
    input_list = input_str.split()
    return max(input_list, key=len)

longestWord("I have been good")

output: 'have'
list function for-loop max min
1个回答
0
投票

尝试此代码,将所有项目的len与最大len进行比较,然后将其附加到另一个列表中

def longestWord(input_str):
input_list = input_str.split()
lenght = len(max(input_list, key=len))
allMax=[]
for f in input_list:
    if len(f) == lenght:
       allMax.append(f)
       print(f)
return allMax       

longestWord(“我一直很好”)

© www.soinside.com 2019 - 2024. All rights reserved.