Spencer Alabaugh Spencer Alabaugh - 1 month ago 6
Python Question

String splitting within a list

I'm supposed to create a function called lastfirst() that takes this input:
['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']

Then the function should return a list containing two lists of first names and last names, like this:
[['Len', 'Kate', 'Bob'],['Gerber', 'Fox', 'Dunn']]

I'm not sure why this is causing me so many problems and I've tried so many different ways of figuring it out, but I just can't get it. Any help is appreciated. :)

Answer

first split & strip items to get name/first name couples, then recombine to get proper arrangement, using listcomps

l = ['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']
c = [[y.strip() for y in x.split(",")] for x in l]
result = [[n[1] for n in c],[n[0] for n in c]]

result:

[['Len', 'Kate', 'Bob'], ['Gerber', 'Fox', 'Dunn']]

EDIT: we don't even need the strip part if it's guaranteed that the separation is ", ", because split accepts a multichar string argument. In that case it's even simpler:

l = ['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']
c = [x.split(", ") for x in l]
result = [[n[1] for n in c],[n[0] for n in c]]