split - Extract surnames from a string with names in python -


i have string names separated word "and" typed in 2 forms: "first last" or "last, first". want generate list surnames sorted alphabetically. i'm new python wondering if there shorter or better way of doing i've done:

names = 'john foo , baz, mike tom , bar foo, s. p.'  authors  = [ i.strip() in names.split("and") ] comma = [ i.split(',')[0] in [i in authors if "," in i] ] nocomma = [ i.split()[-1] in [i in authors if not "," in i] ] surnames = comma + nocomma surnames.sort() print surnames 

there in fact few things can improve:

  • you should split ' , ' avoid splitting names contain letters and (this way,trim no longer needed)
  • the double for loop in 2 list comprehensions not needed
  • if move if left of list comprehension, need 1 of them

finally, can put whole thing in 1 longer list comprehension, if like:

surnames = sorted(i.split(",")[0] if "," in else i.split()[-1]                   in names.split(" , ")) 

note, however, still work if persons multiple surnames written using comma-separated style.


Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -