Switch Lastname, Firstname to Firstname Lastname inside List
python, python-2.7
Solution
You can swap the order in the list of names with:
[" ".join(n.split(", ")[::-1]) for n in namelist]
An explanation: this is a list comprehension that does something to each item. Here are a few intermediate versions and what they would return:
namelist = ["Robinson, David", "Roberts, Tim"]
# split each item into a list, around the commas:
[n.split(", ") for n in namelist]
# [['Robinson', 'David'], ['Roberts', 'Tim']]
# reverse the split up list:
[n.split(", ")[::-1] for n in namelist]
# [['David', 'Robinson'], ['Tim', 'Roberts']]
# join it back together with a space:
[" ".join(n.split(", ")[::-1]) for n in namelist]
# ['David Robinson', 'Tim Roberts']
Problem
I have two lists of sports players. One is structured simply: ``` ['Lastname, Firstname', 'Lastname2, Firstname2'..] ``` The second is a list of lists structured: ``` [['Firstname Lastname', 'Team', 'Position', 'Ranking']...] ``` I ultimately want to search the contents of the second list and pull the info if there is a matching name from the first list. I need to swap 'Lastname, Firstname' to 'Firstname Lastname' to match list 2's formatting for simplification. Any help would be great. Thanks!