-2

In Python, I used to get first element of a 2-d list by

a = [[0, 1], [2, 3]]
a[:][0]
# [0, 2]

Now, the list is sort of complex, the way to get the first elements does not work

a = [['sad', 1], ['dsads', 2]]
a[:][0]
# ['sad', 1]

I do not know what is the difference here. And how to get the first elements in this simple way, rather than

[e[0] for e in a]
Toomatoo
  • 67
  • 6

2 Answers2

5

you could use in-built zip :

aggregates elements from each of the iterables

a = [['sad', 1], ['dsads', 2]]
zip(*a)[0]

#results :
('sad', 'dsads')

You can convert the final result to list from tuple if necessary. * is used to flatten the list into its elements - zip accepts iterables as positional arguments. zip is sort of matrix transposition.

As commented, your first solution (a[:][0]) is not correct, it simply takes the first element of the list. Here you need to first transform the list such that each first elements are grouped into separate list, and so on for second, third .. elements. Then take the first element.

Update:

From @Rawing's comment: If the list is very large, consider using

next(itertools.izip(*a))

This is the iterator version - this takes the list element only as necessary. In this case, it constructs each elment of the result one at a time, since we need the first element, we use next a single time to get the next (thus, first here) element of the iterator.

DurgaDatta
  • 3,952
  • 4
  • 27
  • 34
  • 2
    If the list is very large, consider using `next(itertools.izip(*a))` instead. – Aran-Fey Jul 19 '16 at 06:45
  • @Rawing is right. python-2.7 doesn't use iterators by default so `itertools` version is better. Also the `six` module could be used to guarantee compatibility between python2 and python3 iterables preferences. – frist Jul 19 '16 at 06:51
1

Using numpy :

>>> a = [['sad', 1], ['dsads', 2]]

>>> import numpy

>>> my_array = numpy.array(a)

>>> print my_array[:,0]
['sad' 'dsads']
Ram K
  • 1,746
  • 2
  • 14
  • 23