How to transpose a list in python

Viewed 53

I have the following list: ['123456789', '234567891', '345678912', '456789123', '567891234', '789123456', '891234567', '912345678']

I am trying to create 9 separate list from this one, each containing the first, second, third element of each of the elements of this list. The list should contain ints,for example the first two lists would be:

[1,2,3,4,5,6,7,8,9]
[2,3,4,5,6,7,8,9,1]

I realise the two lists are just the first two elements of the main lists with ints. But I'm trying to create them from the only the first&second element of each of the elements in the big list, so I think some for loop is needed.

5 Answers
startList = ['123456789', '234567891', '345678912', '456789123', '567891234', '789123456', '891234567', '912345678']
finalLists = list(map(lambda x: list(map(lambda y: int(y), list(x))), startList))
print(finalLists)

Using loops:

startList = ['123456789', '234567891', '345678912', '456789123', '567891234', '789123456', '891234567', '912345678']
finalLists = []
for splittingList in startList:
    workingList = []
    for character in splittingList: workingList.append(int(character))
    finalLists.append(workingList)

print(finalLists)

Another possible solution:

[list(map(int, x)) for x in lst]

Output:

[[1, 2, 3, 4, 5, 6, 7, 8, 9], 
[2, 3, 4, 5, 6, 7, 8, 9, 1], 
[3, 4, 5, 6, 7, 8, 9, 1, 2],
[4, 5, 6, 7, 8, 9, 1, 2, 3], 
[5, 6, 7, 8, 9, 1, 2, 3, 4], 
[7, 8, 9, 1, 2, 3, 4, 5, 6], 
[8, 9, 1, 2, 3, 4, 5, 6, 7], 
[9, 1, 2, 3, 4, 5, 6, 7, 8]]

If you like one liners.

a_list = ['123456789', '234567891', '345678912', '456789123', '567891234', '789123456', '891234567', '912345678']

new_list = [[int(character) for character in string] for string in a_list]

Output

[[1, 2, 3, 4, 5, 6, 7, 8, 9],
 [2, 3, 4, 5, 6, 7, 8, 9, 1],
 [3, 4, 5, 6, 7, 8, 9, 1, 2],
 [4, 5, 6, 7, 8, 9, 1, 2, 3],
 [5, 6, 7, 8, 9, 1, 2, 3, 4],
 [7, 8, 9, 1, 2, 3, 4, 5, 6],
 [8, 9, 1, 2, 3, 4, 5, 6, 7],
 [9, 1, 2, 3, 4, 5, 6, 7, 8]]

This would do so with a for loop:

s = ['123456789', '234567891', '345678912', '456789123', '567891234', '789123456', '891234567', '912345678']

new_list = []
for i in s[:2]:
    new_list.append([int(x) for x in i])
Related