Search code examples
pythonlisttransformation

Changing text within a list


I'm attempting to change values in my list of strings.

I want to change these names in my list from Last, First M to First Last while keeping these as a list type (ie don't transform to a data frame then back to a list.

My current list looks like this.

current_list = ["Sanchez, Rick", "Rick, Killer", "Smith, Morty S O L", "Smith, Summer J", "Clockberg Jr., Revolio", "van Womg, Peter", "Lynn-Marie, Sam", "Parker II, Peter"]

This is what I want my finished list to look like.

transformed_list = ["Rick Sanchez", "Killer Rick", "Morty Smith", "Summer Smith", "Revolio Clockberg", "Peter Womg", "Sam Lynn-Marie", "Peter Parker"]

I learned using a lambda function works with dataframes but this won't work because lists don't have an attribute apply to them.

This is what I would have done if the list was a df. I feel like it's something similar but I'm not sure.

transformed_list = current_list.apply(
                                        lambda x: x.split()[2] + ", " + x.split()[0] + " " + x.split()[1]
                                        if len(x.split()) == 3
                                        else x.split()[1] + ", " + x.split()[0]
                                     )

Solution

  • You can use a list comprehension. Split each string at ", ", then rejoin in reversed ([::-1]) order.

    [" ".join(n.split(", ")[::-1]) for n in current_list]
    

    To get only the first part of the last name, you can do something like this (though then you'd need to treat the "van Womg" separately – I'm not sure if an ad-hoc solution will do the trick across the board).

    [" ".join([x.split()[0] for  x in n.split(", ")][::-1]) for n in current_list]