Switch Lastname, Firstname to Firstname Lastname inside List

后端 未结 1 1891
别跟我提以往
别跟我提以往 2021-01-21 06:34

I have two lists of sports players. One is structured simply:

[\'Lastname, Firstname\', \'Lastname2, Firstname2\'..]

The second is a list of li

相关标签:
1条回答
  • 2021-01-21 07:15

    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']
    
    0 讨论(0)
提交回复
热议问题