Creating a 2d Grid in Python

Question:

I am trying to create a 2d array or list or something in Python. I am very new to the language, so I do not know all the ins and outs and different types or libraries.

Basically, I have a square list of lists, g, and I want to transpose it (turn rows into columns and columns into rows). Later I will be traversing this list of lists and the transposed list of lists. In the transposed list, the order of the columns does not matter. Is this the “Python way”? Is there a much faster way to do this?

I like using lists because I am comfortable with the syntax that is so similar to arrays in the languages I know, but if there is a better way in Python, I would like to learn it.

def makeLRGrid(g):
    n = []
    for i in range(len(g)):
        temp = []
        for j in range(len(g)):
            temp.append(g[j][i])
        n.append(temp)
    return n

Thank you for any help you can offer!

Edit: Sorry for the confusion, apparently I mean transpose, not invert!

Asked By: William

||

Answers:

This implementation does the same as yours for "square" lists of lists:

def makeLRGrid(g):
    return [row[:] for row in g]

A list can be copied by slicing the whole list with [:], and you can use a list comprehension to do this for every row.

Edit: You seem to be actually aiming at transposing the list of lists. This can be done with zip():

def transpose(g):
    return zip(*g)

or, if you really need a list of lists

def transpose(g):
    return map(list, zip(*g))

See also the documentation of zip().

Answered By: Sven Marnach

For numerical programming I would strongly recommend NumPy (and the related SciPy). NumPy implements very fast multi-dimensional arrays. Have a look at here for the available array manipulation routines.

Answered By: Chris

I guess invert the list of lists is like this:

g = [[1,2,3], [4,5,6], [7,8,9]]
result = [p[::-1] for p in g]
print result

Output:

[[3,2,1], [6,5,4], [9,8,7]]

Maybe I'm worry. Can you give some example?

EDIT: for the comment example

result = [list(p) for p in zip(*g)]
print result

Output:

[[1,4,7], [2,5,8], [3,6,9]]
Answered By: shihongzhi

To add to Chris's comment, I really cannot recommend numpy enough. You say it is for one project, but you will probably make use of it many times over for the sake of learning some (simple) syntax just once.

For example if you have a list of lists g:

g = [[1,2,3],[4,5,6],[7,8,9]]

You can make this into an array simply by:

>>> import numpy as np
>>> g_array = np.array(g)
>>> g_array
array([[1, 2, 3],
      [4, 5, 6],
      [7, 8, 9]])

access any item by simply:

>>> g_array[0,1]
2
>>> g_array[1,2]
6

and perform your 'invert' (actually transpose- i.e. row one becomes column one up to for each row) by:

>>> g_transpose = g_array.transpose() # or  = g_array.T from Simon's comment
>>> g_transpose
array([[1, 4, 7],
      [2, 5, 8],
      [3, 6, 9]])
Answered By: Jdog