How could I transform nested lists?

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

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

where the numbers are tiles. Then I do it with a whole 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 creates an array in the format [row] [column], but I would prefer it to be [column] [row], as in [x] [y], so I would not have to reverse it (i.e. [ Y] [X]). But I can’t come up with any brief ways to solve this problem. I looked at refining the format using xml syntax via Tiled, but for a beginner it seems too complicated.

Thanks in advance for any answers.

+6
source share
2 answers

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]).

+26
source
 def listTranspose( x ): """ Interpret list of lists as a matrix and transpose """ tups = zip( *x ) return [ list(t) for t in tups ] 
0
source

Source: https://habr.com/ru/post/896672/


All Articles