Python: first element in a nested list

10,694

Solution 1

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]

Solution 2

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]]

Solution 3

You can use numpy array with transpose function aswell.

import numpy as np
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]] ]
Lnumpy = np.array(L)
Ltransposed = Lnumpy.transpose(0, 2, 1) # Order of axis

Output is now

[[[0 3 6]
  [1 4 7]
  [2 5 8]]

 [[0 3 6]
  [1 4 7]
  [2 5 8]]

 [[0 3 6]
  [1 4 7]
  [2 5 8]]]

Now you don't need every first member of member, but just the first member.

print(Ltransposed[0][0]) now gives you [0, 3, 6] Then

for i in ltr:
    print(ltr[0][0])

Outputs

[0 3 6]
[0 3 6]
[0 3 6]

Just for detail, there is also possibility of using zip...(here for Python 3...)

print(list(zip(*Ltransposed))[0])

Gives you the same. If you need list, convert it back... list()...

Share:
10,694
lara
Author by

lara

Updated on June 04, 2022

Comments

  • lara
    lara almost 2 years

    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?