如何在Python中找到列表中最短的字符串

时间:2011-08-29 10:30:11

标签: python

这似乎是一个非常简单的问题,但我正在寻找一种简短易用的方法,这仍然是可以理解的(这不是代码高尔夫)。

给定一个字符串列表,找到最短字符串的最简单方法是什么?

对我来说最明显的方式大致是:

l = [...some strings...]
lens = map(l, len)
minlen, minind = min(lens)
shortest = l[minind]

但这似乎是这个问题的很多代码(至少在python中)。

6 个答案:

答案 0 :(得分:83)

The min function有一个可选参数key,可让您指定一个函数来确定每个项目的“排序值”。我们只需将其设置为the len function即可获得最短的值:

strings = ["some", "example", "words", "that", "i", "am", "fond", "of"]

print min(strings, key=len) # prints "i"

答案 1 :(得分:2)

需要线性时间:

   reduce(lambda x, y: x if len(x) < len(y) else y, l)

答案 2 :(得分:1)

我使用sorted(l, key=len)[0]

答案 3 :(得分:0)

可能的答案:

l = [...some strings...]
l.sort(key=len)
shortest = l[0]

然而,这可能是非常低效的,因为它对整个列表进行排序,这是不必要的。我们真的只需要最低限度。

答案 4 :(得分:0)

如其他答案所示,这些解决方案需要线性时间。不过,他们需要防范空的可迭代对象:

import functools

strings = ["small str", "xs", "long string"]

if (strings):
    print( "shortest string:", functools.reduce(lambda x, y: x if len(x) < len(y) else y, strings) )
    # or if you use min:
    # print( "shortest string:", min(strings, key=len) )
else:
    print( "list of strings is empty" )

答案 5 :(得分:-1)

arr=('bibhu','prasanna','behera','jhgffgfgfgfg')
str1=''

#print (len(str))
for ele in arr:
    print (ele,ele[::-1])
    if len(ele)>len(str1):
        str1=ele
    elif len(ele)<len(str2):
        str2=ele
print ("the longest element is :",str1)
str2=arr[0]
for ele in arr:
    if len(ele)<len(str2):
        str2=ele

print ("the shortest element is :",str2)