列表中最长的字符串

时间:2012-12-20 03:00:48

标签: python

我正在创建一个从列表中返回最长字符串值的函数。当只有一个字符串最多的字符串时,我的代码才有效。我试图让它打印所有最长的字符串,如果有多个字符串,我不希望它们被重复。当我运行它时,它只返回'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)

5 个答案:

答案 0 :(得分:22)

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

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

一点解释。这称为list comprehension,它允许您理解一个列表作为另一个列表。代码[len(s) for s in stringlist]表示“通过stringlist生成类似列表的对象,而对于该列表中的每个s,请改为给我len(s)(长度为{1}}字符串)。

现在我们有一个列表[2, 5, 3, 5, 5, 5]。然后我们调用内置的max()函数,它将返回5

现在您拥有最大长度,您可以过滤原始列表:

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

这就像用英文读的那样:“对于stringlist中的每个字符串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类型名称的含义。

答案 1 :(得分:11)

我高度赞同乔纳森莱因哈特的回答,但我无法忍住......这个怎么样?

max(map(len, stringlist))

没有必要写一个列表理解,这甚至更简单......

答案 2 :(得分:0)

也许你误写了行if item not in list:,并且缩进错了,修改如下:

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 ans:
                answer = answer + " " + item
    return answer

但我认为Jonathon Reinhart提供了一种更好的方法。

答案 3 :(得分:0)

我有同样的问题。我用这种方式想出了我的解决方案:

myList =['hi', 'hello', 'hey','ohman', 'yoloo', 'hello']
def get_longest_strings(myList):
        longest=len(max(myList,key=len))
        for each in myList:
                if(longest==len(each)):
                       #common_result is list to store longest string in list
                       common_result.append(each)
        return common_result
print(common_result)

答案 4 :(得分:0)

这样的东西...

def allLongestStrings(inputArray):
    maxLength = len(max(inputArray, key = len))
    
    newArray = []
    
    lengthArray = len(inputArray)
    
    for i in range(lengthArray):
        if(len(inputArray[i])==maxLength):
            newArray.append(inputArray[i])
    return newArray