How to find the shortest string in a list in Python

后端 未结 6 616
星月不相逢
星月不相逢 2020-12-02 19:53

This seems like a pretty simple problem, but I\'m looking for a short and sweet way of doing it that is still understandable (this isn\'t code golf).

Given a list of

相关标签:
6条回答
  • 2020-12-02 20:25

    The min function has an optional parameter key that lets you specify a function to determine the "sorting value" of each item. We just need to set this to the len function to get the shortest value:

    strings = ["some", "example", "words", "that", "i", "am", "fond", "of"]
    
    print min(strings, key=len) # prints "i"
    
    0 讨论(0)
  • 2020-12-02 20:28
    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) 
    
    0 讨论(0)
  • 2020-12-02 20:33

    I'd use sorted(l, key=len)[0]

    0 讨论(0)
  • 2020-12-02 20:33

    Potential answer:

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

    However, this is probably very inefficient in that it sorts the entire list, which is unnecessary. We really just need the minimum.

    0 讨论(0)
  • 2020-12-02 20:39

    As suggested in other answers, these solutions takes linear time. They need need to be guarded against empty iterables though:

    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" )
    
    0 讨论(0)
  • 2020-12-02 20:45

    Takes linear time:

       reduce(lambda x, y: x if len(x) < len(y) else y, l)
    
    0 讨论(0)
提交回复
热议问题