0

I have data with (x,y) coordinates that origins in the lefttop corner. I turn into a matrix with indexes starting from 0 that looks like that:

| 0 | 1 | 2 | 3 | 4|
| 5 | 6 | 7 | 8 | 9|
|10 |11 |12 |13 |14|
|15 |16 |17 |18 |19|
|20 |21 |22 |23 |24|

for example (x,y)=(1,4) id = y*5 + x = 21. But i want it to origin in the left bottom so that i obtain a matrix with indexing like that:

| 20| 21| 22| 23| 24|
| 15| 16| 17| 18| 19|
| 10| 11| 12| 13| 14|
| 5 | 6 | 7 | 8 |  9|
| 0 | 1 | 2 | 3 |  4|

so basically reversing the rows. Is there a way to do that in pythonic way? What would be the most computationally efficient way to achieve it otherwise?

5 Answers 5

1

I am not sure about whether "Pythonic" or not, but the most direct and efficient way to me is simply just:

u = [v[5 * (len(v) // 5 - i // 5 - 1) + i % 5] for i in xrange(len(v))]

EDIT:

If you feel uncomfortable about these divisions and modulos, an alternative without any math calculation(but might be less efficient) is:

sum([v[i: i+5] for i in xrange(0, len(v), 5)][::-1], [])

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

Comments

0

I don't know how pythonic this is, but it works fine

for i in len(v)//2:
      v[i], v[-i] = v[-i], v[i]

Comments

0

Reverse the array by x

>>> M = [[0,1,2],[3,4,5],[6,7,8],[9,10,11]]
>>> M[::-1]
[[9, 10, 11], [6, 7, 8], [3, 4, 5], [0, 1, 2]]

Comments

0

Use either list(reversed(x)) or x[::-1] like:

matrix=[[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14],[15,16,17,18,19]]
backwards=matrix[::-1]
inverted=list(reversed(matrix))

reversed returns a backwards iterator that list converts to a list, and [::-1] returns a list splice taking the elements backwards.

Comments

0

When the shape of your matrix is width, height = 5, 5, the general formula to get the bottom up index from the list index is:

width*(height-index//height-1)+index%height

Comments

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.