How do I access the 1st element of each list in a lists of lists
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 acce开发者_如何学Pythonss 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'].
Try a list comprehension:
# (numbers, letters) can be replaced with `list_of_lists`
>>> [ x[0] for x in (numbers, letters) ]
['1', 'a']
import operator
map(operator.itemgetter(0), [numbers, letters])
list_of_lists = [['1', '2', '3'], ['a', 'b', 'c']]
list_of_firsts = [l[0] for l in list_of_lists]
You may be looking for zip
I would try:
zip(*list_of_lists)[0]
精彩评论