Doubt to transpose part of a table with Python

2

I need help to build a Python script that transposes part of a csv as in the example below:

[[0A,0B,0C,0D,0E,0F]
[01,02,03,04,05,06]
[07,08,09,10,11,12]
[13,14,15,16,17,18]
[19,20,21,22,23,24]]

in this:

[[0A,0B,0C]
[01,02,03]
[01,02,04]
[01,02,05]
[01,02,06]
[07,08,09]
[07,08,10]
[07,08,11]
.
.
.
[19,20,24]]

Has anyone ever done this kind of transposition of a csv / xls via python?

    
asked by anonymous 30.06.2015 / 18:30

1 answer

1

Using map and chain :

from itertools import chain

data = [[10,11,12,13,14,15],
[1,2,3,4,5,6],
[7,8,9,10,11,12],
[13,14,15,16,17,18],
[19,20,21,22,23,24]]

result = chain(*map(lambda line: [line[:2] + [line[i]] for i in range(2, 6)], data))
print(list(result))

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

Instead of chain , you can use sum if you do not want to import anything:

result = sum(map(lambda line: [line[:2] + [line[i]] for i in range(2, 6)], data), [])
    
30.06.2015 / 18:48