Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: first element in a nested list

I would like a list that contains only the first elements of the nested list. The nested list L, it's look like:

L =[ [[0,1,2],[3,4,5],[6,7,8]], [[0,1,2],[3,4,5],[6,7,8]], [[0,1,2],[3,4,5],[6,7,8]] ]

for l in L:
 for t in l:
  R.append(t[0])
print 'R=', R

The Output is R= [0, 3, 6, 0, 3, 6, 0, 3, 6] but I want to get a separated result like:

R= [[0, 3, 6], [0, 3, 6], [0, 3, 6]]

I've also tried through a list comprehension like [[R.append(t[0]) for t in l] for l in L] but this gives [[None, None, None], [None, None, None], [None, None, None]]

What is wrong?

like image 433
lara Avatar asked Dec 20 '22 11:12

lara


2 Answers

Your solution returned [[None, None, None], [None, None, None], [None, None, None]] because the method append returns the value None. Replacing it by t[0] should do the trick.

What you're looking for is:

R = [[t[0] for t in l] for l in L]
like image 67
Hetzroni Avatar answered Dec 31 '22 14:12

Hetzroni


You could do it like this:

>>> L = [ [[0,1,2],[3,4,5],[6,7,8]], [[0,1,2],[3,4,5],[6,7,8]], [[0,1,2],[3,4,5],[6,7,8]] ]
>>> R = [ [x[0] for x in sl ] for sl in L ]
>>> print R
[[0, 3, 6], [0, 3, 6], [0, 3, 6]]
like image 21
isedev Avatar answered Dec 31 '22 15:12

isedev