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!
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().
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