String splitting within a list
<p>I'm supposed to create a function called <code>lastfirst()</code> that takes this input:
<code>['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']</code></p>

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

<p>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. :)</p>

<p>first split &amp; strip items to get name/first name couples, then recombine to get proper arrangement, using listcomps</p>

<pre><code>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]]
</code></pre>

<p>result:</p>

<pre><code>[['Len', 'Kate', 'Bob'], ['Gerber', 'Fox', 'Dunn']]
</code></pre>

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

<pre><code>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]]
</code></pre>

python