1

Example:

numbers = ['1','2','3']
letters = ['a','b','c']

I want to get [1,a] as a results. Yeah I can loop through it, but I'm wondering if there is a fast one line way of doing this.

EDIT EDIT !!!!

I made a horrible mistake in describing the problem.

I have access to the combined list (the list of lists of the question):

list_of_lists = [ numbers, letters]

which is equal to:

[ ['1','2','3'],['a','b','c']]

Sorry for the confusion. The end result is still the same, this would be ['1','a'].

miku
  • 181,842
  • 47
  • 306
  • 310
Peter
  • 41
  • 5
  • 1
    http://stackoverflow.com/questions/2054416/getting-the-first-elements-per-row-in-an-array-in-python. Someone else asked for the answer to the same homework problem before you. – S.Lott Jan 27 '11 at 20:19
  • 1
    Is your question related to some bigger context, if so please elaborate us. Just commented because you are refering to looping, but clearly the solution you are looking for doesen't need any looping, thanks – eat Jan 27 '11 at 20:48
  • OK took me forever to find the add comment. Well I've looked at the homework and that's exactly how I should do it. I'm using the solution to grab the description names from a MySQL description query. You know, cause they decided that the attributes should be part of it too. – Peter Jan 27 '11 at 22:05

5 Answers5

7

Try a list comprehension:

# (numbers, letters) can be replaced with `list_of_lists` 
>>> [ x[0] for x in (numbers, letters) ] 
['1', 'a']
miku
  • 181,842
  • 47
  • 306
  • 310
  • Why upvoted? Clearly OP's question (as stated now) has a constant time solution. Or is your answer some kind of joke? thanks – eat Jan 27 '11 at 20:57
  • 1
    @eat: No, no joke, just the an answer, that worked with the previous version of the question (and still works). Besides, it's in the same complexity class as your answer. – miku Jan 27 '11 at 21:03
  • @The MYYN OK, then perhaps I'll misunderstod something. Do you consider my answer giving wrong solution? Why list comprehension seems to be the right answer? Clearly no iterations needed. I'm just concernd because I felt that OP was looking for something not stated in the question yet ;-). – eat Jan 27 '11 at 21:21
  • @eat: No, your answer is fine. I would have upvoted it, if it just said `[ list_of_list[0][0], list_of_list[1][0] ]`, but the rest is a bit noisy (at the moment). To me, list comprehension looks a bit cleaner (and it is actually shorter). – miku Jan 27 '11 at 21:27
2
import operator
map(operator.itemgetter(0), [numbers, letters])
ephemient
  • 198,619
  • 38
  • 280
  • 391
0
list_of_lists = [['1', '2', '3'], ['a', 'b', 'c']]
list_of_firsts = [l[0] for l in list_of_lists]
Jay Conrod
  • 28,943
  • 19
  • 98
  • 110
-1

You may be looking for zip

Confusion
  • 16,256
  • 8
  • 46
  • 71
-1

I would try:

zip(*list_of_lists)[0]
rubik
  • 8,814
  • 9
  • 58
  • 88