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?
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]
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With