how do I sort a list of names?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • anderson1373
    New Member
    • Nov 2009
    • 23

    #1

    how do I sort a list of names?

    I need to sort a list of first and last names from shortest to longest.
    for example:
    [John Doe, Jane Smith, Jane Doe]

    I have to write a function to find the longest name but noe sure how to do it!
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    In Python 2.3:
    Code:
    >>> names = ["John Doe", "Jane Smith", "Jane Doe", "Jo Nu"]
    >>> names.sort(lambda x, y: cmp(len(x), len(y)))
    >>> names
    ['Jo Nu', 'John Doe', 'Jane Doe', 'Jane Smith']
    >>>

    Comment

    • dwblas
      Recognized Expert Contributor
      • May 2008
      • 626

      #3
      I have to write a function to find the longest name but no(t) sure how to do it!
      Do you want to sort or to find the longest name. Sorting the entire list just to find one item is very inefficient and if I was your instructor, would be rejected as too inefficient to be a viable solution.
      Code:
      ##   does not allow for multiple names that are longest
      names = ['Jon Doe', 'Jane Smith', 'Jane Doe']
      longest_name = names[0]
      longest = len(names[0])
      
      for name in names:
          if len(name) > longest:
              longest = len(name)
              longest_name = name
      print longest_name, longest

      Comment

      Working...