1

I have an array a, which is twodimensional. A contains objects which also contain objects. I want to make sure that a[1,1] becomes a[n,n], a[2,1] becomes a[n-1,n], a[2,2] becomes a[n-1][n-1] etc. I wrote the following code to do this:

tempArray = copy(self.topArea)
for y in range(0,len(tempArray)):
    for x in range(0,len(tempArray[y])):
        self.topArea[y][x] = tempArray[len(tempArray)-1-y][len(tempArray[y])-1-x]

But this achieves litteraly nothing. Deepcopying also does not help: the array does not get inverted.

How can I invert it?

3
  • Is this a numpy array, or are you using the wrong word for a list? Commented Jun 12, 2013 at 12:51
  • Also note that iterating by index is a terrible idea in Python - it is slow, inefficient, inflexible and hard to read. Python is designed to iterate by value, not index. Commented Jun 12, 2013 at 12:53
  • Can you give a little better definition of inversing? At first, I answered showing how to take the transpose, but now I think that isn't what you want ... Commented Jun 12, 2013 at 12:57

1 Answer 1

3

Do you want something like:

tempArray = [list(reversed(x)) for x in reversed(self.topArea)]

If everything is lists, you could also do:

tempArray = [x[::-1] for x in reversed(self.topArea)]

for a possible speed boost.

Sign up to request clarification or add additional context in comments.

3 Comments

tempArray = [x[::-1] for x in self.topArea[::-1]] ?
@SylvainLeroux reversed is memory efficient as it returns an iterator.
Also, presumably, reversed should work for more objects. I'm not sure if I've found that to be true in actual practice, but any sequence can be reversed (including xrange which you can't slice)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.