Home > OS >  Changing text within a list
Changing text within a list

Time:06-11

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]
                                     )

CodePudding user response:

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]

CodePudding user response:

First you have to assign a key to each part of the list, for instance Sanchez would be 0 and Rick would be 1. Then when assigning your output simply place a -1 on the third (ie. [0,0,-1] ) and that should reverse the order and keep them in the list.

CodePudding user response:

transformed_list = [x.split()[2]   ", "   x.split()[0]   " "   x.split()[1]
                    if len(x.split()) == 3 else x.split()[1]   ", "   x.split()[0] 
                    for x in current_list]

Would this work?

CodePudding user response:

You could do this with a list comprehension and the inbuilt string.split() method. The split method splits a string around the given characters, you can rejoin them in the order you want.

[s.split(', ' for s in current_list]

Will give you a list of lists, where we've changed e.g. "Sanchez, Rick" into ['Sanchez', 'Rick']

We can then iterate over this list in another list comprehension to give us what we want:

[' '.join([b, a]) for a, b in [s.split(', ' for s in current_list]]

We use the join method to join the two strings [b, a] with a space ' ', and we have set a and b to be the strings in our intermediate list.

  • Related