mercredi 5 mai 2021

Conditional statement to pull out last names from a list

I have a list of full names (titled "FullNames") and I am trying to pull out the last names. The problem is that some of the full names include middle names (e.g., some of the items in the list are "Craig Nelson" while others are "Craig T. Nelson") which stops me from using a simple list comprehension statement such as:

LastNames = ([x.split()[1] for x in FullNames])

Instead, I am trying to loop through the list with this code:

LastNames = []
for item in FullNames:
    if '.' in FullNames:
        LastNames.appened(item[2])
    else:
        LastNames.append(item[1])
print(LastNames)

However, I am just getting a bunch of letters back:

['u', 'a', 'e', 'i', 'o', 'a', 't', 'h', 'r', 'e', 'e', 'r', 'e', 'h', 'a', 'i', 't', 'a', 'r', 'a', 'i', 'e', 'o', 'e', 'e', 'a', 'r', 'o', 'a', 'y', 'i', 'e', 'e', 'o', 'o', 'e', 'e', 'a', 'i', 'i', 'e', 'm', 'a', 'a', 'a', 'n', 'e', 'a', 'r']

Is there a simple way around this?

Aucun commentaire:

Enregistrer un commentaire