0

I wrote this program, where I need to make a list of names, with last names alphabetized, and first names in front of it. This is what I did so far:

firstnames = ['good', 'bad', 'tall', 'big']
lastnames = ['boy', 'girl', 'guy', 'man']
list3 = [a + b for a, b in zip(firstnames, lastnames)]
l3 = sorted(list3)
n = len(l3)
l4 = zip(*[l3])
print l3
print l4

the zip* makes the elements into tuples, but how do I separate the elements again, and join them in a different order?

Kimi Lee
  • 43
  • 2
  • 9
  • what version of Python are you using? – acutesoftware Sep 26 '13 at 15:28
  • 1
    What output would you like? The code that you have *seems* like you want to just have another copy of the list, which you can accomplish using `l4 = l3[:]` or a host of other methods. – Wayne Werner Sep 26 '13 at 15:29
  • How could you separate the items again? `l3` is `['badgirl', 'bigman', 'goodboy', 'tallguy']`: you've concatenated the strings together. How could the code know to separate `goodboy` into `good` and `boy`? – David Robinson Sep 26 '13 at 15:30
  • possible duplicate of [A Transpose/Unzip Function in Python (inverse of zip)](http://stackoverflow.com/questions/19339/a-transpose-unzip-function-in-python-inverse-of-zip) – Saullo G. P. Castro Sep 26 '13 at 15:32
  • oh sorry I'm using 2.7 – Kimi Lee Sep 26 '13 at 15:51

2 Answers2

2

Once you've done a+b you can't separate them. You've concatenated the strings together, and there's nothing in the result to indicate what part of the string is the firstname and what part the lastname.

Do your sorting on the tuples that come from zip:

print sorted(zip(firstnames, lastnames), key = lambda pair: pair[1])

One they're sorted, you can concatenate the strings.

Also, be aware that you could just zip them in the other order, then they'll sort on the lastname without needing to specify key:

print [b + a for a, b in sorted(zip(lastnames, firstnames))]
Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
1

I think you just need to use zip once:

ans = ['%s %s' % (first, last) for (first, last) in zip(firstnames, sorted(lastnames))]
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
nofinator
  • 2,906
  • 21
  • 25