列表中最长的字符串

fif*_*man 11 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)
Run Code Online (Sandbox Code Playgroud)

Jon*_*art 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
Run Code Online (Sandbox Code Playgroud)

一点解释.这称为列表推导,它允许您将一个列表理解为另一个列表.代码 [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]
Run Code Online (Sandbox Code Playgroud)

这就像读英文一样:"对于sstringlist中的每个字符串,给我字符串s,如果len(s)等于maxlength."

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

unique_longest_strings = list(set(longest_strings))
Run Code Online (Sandbox Code Playgroud)

(我们list()打算在删除重复项后将其重新转换为列表.)


这归结为:

ml = max(len(s) for s in stringlist)
result = list(set(s for s in stringlist if len(s) == ml))
Run Code Online (Sandbox Code Playgroud)

注意:不要使用名为的变量list,因为它会覆盖该list类型名称的含义.

  • @JonathonReinhart它实际上并不是列表理解.它是[生成器表达式](http://docs.python.org/2/reference/expressions.html#generator-expressions). (2认同)

PAL*_*LEN 11

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

max(map(len, stringlist))
Run Code Online (Sandbox Code Playgroud)

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