Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the first elements per row in an array in Python?

Tags:

python

tuples

Let's say i have an array of Tuples, s, in the form of:

s = ((1, 23, 34),(2, 34, 44), (3, 444, 234))

and i want to return another Tuple, t, consisting of the first element per row:

t = (1, 2, 3)

Which would be the most efficient method to do this? I could of course just iterate through s, but is there any slicker way of doing it?

like image 571
c00kiemonster Avatar asked Jan 13 '10 04:01

c00kiemonster


People also ask

How do you select the first element of an array in Python?

In Python lists are zero-indexed, so the first element is available at index 0 . Similarly, we can also use the slicing syntax [:1] to get the first element of a list in Python.

How do you get the first element in a two dimensional list?

Finding the first element in a 2-D list can be rephrased as find the first column in the 2d list. Because your data structure is a list of rows , an easy way of sampling the value at the first index in every row is just by transposing the matrix and sampling the first list.

How do you get the first element of an integer in Python?

S1[0] gives you the first element.


Video Answer


3 Answers

No.

t = tuple(x[0] for x in s)
like image 81
Ignacio Vazquez-Abrams Avatar answered Oct 31 '22 12:10

Ignacio Vazquez-Abrams


The list comprehension method given by Ignacio is the cleanest.

Just for kicks, you could also do:

zip(*s)[0]

*s expands s into a list of arguments. So it is equivalent to

zip( (1, 23, 34),(2, 34, 44), (3, 444, 234))

And zip returns n tuples where each tuple contains the nth item from each list.

like image 24
HS. Avatar answered Oct 31 '22 12:10

HS.


import itertools
s = ((1, 23, 34),(2, 34, 44), (3, 444, 234))
print(next(itertools.izip(*s)))

itertools.izip returns an iterator. The next function returns the next (and in this case, first) element from the iterator.

In Python 2.x, zip returns a tuple. izip uses less memory since iterators do not generate their contents until needed.

In Python 3, zip returns an iterator.

like image 34
unutbu Avatar answered Oct 31 '22 14:10

unutbu