Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch Lastname, Firstname to Firstname Lastname inside List

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!

like image 985
tim roberts Avatar asked Jan 13 '23 19:01

tim roberts


1 Answers

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']
like image 88
David Robinson Avatar answered Jan 19 '23 11:01

David Robinson