列表中最长的字符串

发布于 2021-01-29 18:02:58

我正在做一个从列表中返回最长字符串值的函数。当只有一个包含最多字符的字符串时,我的代码有效。如果有多个字符串,我尝试使其打印所有最长的字符串,并且我不希望重复它们。当我运行它时,它只返回“
hello”,而我希望它也返回“ ohman”和“ yoloo”。我觉得问题就在if item not list:眼前,但是我已经尝试了所有方法,但是没有用。

list = ['hi', 'hello', 'hey','ohman', 'yoloo', 'hello']
def length(lists):
    a = 0 
    answer = ''
    for item in lists:
        x = len(item) 
    if x > a:
        a = x
        answer = item
    elif x == a:
        if item not in list:
            answer = answer + ' ' + item
    return answer
print length(list)
关注者
0
被浏览
152
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    首先 ,我们可以在列表中找到任何字符串的最大长度:

    stringlist = ['hi', 'hello', 'hey','ohman', 'yoloo', 'hello']
    #maxlength = max([len(s) for s in stringlist])
    maxlength = max(len(s) for s in stringlist)  # omitting the brackets causes max 
                                                 # to operate on an iterable, instead
                                                 # of first constructing a full list
                                                 # in memory, which is more efficient
    

    一点解释。这称为列表理解,它使您可以将一个列表 理解 为另一列表。该代码的 [len(s) for s in stringlist]意思是“通过获取来生成类似列表的对象,stringlist而对于s该列表中的每个对象,请给我len(s)(该字符串的长度)。

    现在我们有了清单[2, 5, 3, 5, 5, 5]。然后,我们在其max()上调用内置函数,该函数将返回5

    现在 您已达到最大长度,可以过滤原始列表:

    longest_strings = [s for s in stringlist if len(s) == maxlength]
    

    就像英语中的读法一样:“对于字符串列表s中的每个字符串s,如果len(s)等于,请给我该字符串maxlength。”

    最后
    ,如果要使结果唯一,则可以使用set()构造函数来生成唯一集:

    unique_longest_strings = list(set(longest_strings))
    

    (我们呼吁list()在删除重复项后将其转回列表。)


    归结为:

    ml = max(len(s) for s in stringlist)
    result = list(set(s for s in stringlist if len(s) == ml))
    

    注意 :请勿使用名为的变量list,因为它会覆盖list类型名称的含义。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看