6

I am writing code to parse a tilemap map from a config file. The map is in the format:

1|2|3|4
1|2|3|4
2|3|4|5

where the numbers represent tiles. I then make this into an integer array:

[[int(tile) for tile in row.split("|")] for row in  "1|2|3|4\n1|2|3|4\n2|3|4|5".lstrip("\n").split("\n")]

This produces an array in the format [row][column], but I would prefer it to be [column][row] as in [x][y] so I wouldn't have to address it backwards (i.e. [y][x]). But I can't think of any concise ways of attacking the problem. I have considered reworking the format using xml syntax through Tiled, but it appears too difficult for a beginner.

Thanks in advance for any responses.

agf
  • 171,228
  • 44
  • 289
  • 238
zzz
  • 356
  • 1
  • 4
  • 10
  • possible duplicate of [Matrix Transpose in Python](http://stackoverflow.com/questions/4937491/matrix-transpose-in-python) – Chillar Anand Jul 31 '15 at 10:15

2 Answers2

26

use mylist = zip(*mylist):

>>> original = [[1, 2, 3, 4], [1, 2, 3, 4], [2, 3, 4, 5]]
>>> transposed = zip(*original)
>>> transposed
    [(1, 1, 2), (2, 2, 3), (3, 3, 4), (4, 4, 5)]

>>> original[2][3]
    5

>>> transposed[3][2]
    5  

How it works: zip(*original) is equal to zip(original[0], original[1], original[2]). which in turn is equal to: zip([1, 2, 3, 4], [1, 2, 3, 4], [2, 3, 4, 5]).

Udi
  • 29,222
  • 9
  • 96
  • 129
0
def listTranspose( x ):
    """ Interpret list of lists as a matrix and transpose """ 
    tups = zip( *x )
    return [ list(t) for t in tups ]
Quant
  • 4,253
  • 3
  • 17
  • 15