Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • How to sort a list of strings based upon length
    I generally sort a strings list like below
    arr = ['1','1231','33','44']
    tmp = map(lambda x: return (len(x) ,x) , arr )
    tmp.sort()
    # >>> print tmp
    # [(1, '1'), (2, '33'), (2, '44'), (4, '1231')] 
    sorted_strings_list = [each[1] for each in tmp]
    
    Is there any other way?
    maddula posted this question on 1/23/14 | python, sort
    Answers
  • +
  • 1
  • -
  • Sorry, answered with wrong answer ....
    arr.sort(key = lambda x: len(x))
    
  • +
  • 0
  • -
  • To display code include the following tags:
    arr = ['1','1231','33','44']
    print(sorted(arr, key=len))
    
  • +
  • 0
  • -
  • Here's a cool trick in JS:
    function srtStrLen(arr) {
    arr.sort(function(a,b) {return b.length - a.length});
    return arr;
    }
    srtStrLen(["lrg", "larger", "larg", "largest", "large"]);
    
  • +
  • 0
  • -
  • Try this:
    arr = ['1','1231','33','44']
    tmp=list(map(lambda x:(len(x), x), arr))
    print (tmp)
    
    Log in to write an answer.