0

I have a list like :

L = [11, 15, 18, 20, 22, 25, 30, 35, 40]

of 9 elements. I would like to feed each value to the (ij)th position of a 3 by 3 matrix like

00 01 02
10 11 12
20 21 22

That is 11 should go to (00)th position, 15 should go to (01)th position, 18 should go to (02)th position, 20 should go to (10)th position and so on.

Please suggest me the most efficient way to achieve this using for loop. Because I am writing an YT (http://yt-project.org/) YT data analysis code. YT is a Python package for analyzing astrophysical data.

Inside my code there is a line

axes = axes[i][j]

I want to feed first value in the list to

pf = load(L[0])

when ij is 00 then second value in the list to

pf = load(L[1])

when ij is 01 and so on... Please suggest me the most efficient way to achieve that? thank you

Community
  • 1
  • 1
R S John
  • 507
  • 2
  • 9
  • 16

3 Answers3

2

Use the grouper recipe to collect elements of L into groups of 3:

L = iter(L)
zip(*[L]*3)

For example,

In [11]: L = [11, 15, 18, 20, 22, 25, 30, 35, 40]

In [12]: L = iter(L)

In [13]: zip(*[L]*3)
Out[13]: [(11, 15, 18), (20, 22, 25), (30, 35, 40)]

I'm assuming by "matrix" you mean a list of tuples. It is easy to convert this to a true matrix object (such as numpy.matrix) if that is what you desire.

There is an explanation of the grouper recipe here.

Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0

Using itertools.islice:

>>> L = [11, 15, 18, 20, 22, 25, 30, 35, 40]
>>> from itertools import islice
>>> it = iter(L)
>>> [[x] + list(islice(it, 2)) for x in it]
[[11, 15, 18],
 [20, 22, 25],
 [30, 35, 40]]

Using index based slicing:

>>> [L[i:i+3] for i in xrange(0, len(L), 3)]
[[11, 15, 18],
 [20, 22, 25],
 [30, 35, 40]]
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

If you are okay with numpy which has most of the functionality of matlab you can achieve this by converting list to numpy array. This is also convenient if you are planning for matrix or vector operation. You can then obtain the 2D array by reshaping the 1D array.

In [91]: arr = numpy.array(L).reshape((3,3))

Out[91]: arr
array([[11, 15, 18],
       [20, 22, 25],
       [30, 35, 40]])


In [92]: arr[0]
Out[92]: array([11, 15, 18])

In [93]: arr[0][1]
Out[93]: 15

In [94]: arr[2][2]
Out[94]: 40
mr2ert
  • 5,146
  • 1
  • 21
  • 32
rrb
  • 1
  • 1