Reputation: 193
I need to make a list of lists out of 4 lists I have. However, I want each list to become a column instead of a row in the final list of lists.
Each of my lists is 10 items long, so I have made a an empty list of lists filled with 0s which is 4 by 10.
rows, columns = (10, 4)
biglist = [[0 for i in range(columns)] for j in range(rows)]
I now want to know how to fill the empty list of lists with my individual lists.
Or, would it be better to make 10 new lists by reading each place from each of the four lists one at a time, and then use these new lists to fill in the empty list of lists?
Upvotes: 0
Views: 1468
Reputation: 1299
(Edit) One method is to make a list of lists, and then flip it (Here we don't need the lists of zeros):
array = [[list1],[list2],[list3],[list4]]
def flipper(array):
flipped = [[] for x in range(len(array[0]))]
for y in range(len(array)):
for x in range(len(array[0])):
flipped[x].append(array[y][x])
return flipped
Okay this is working... again assuming all list elements are the same length.
Upvotes: 0
Reputation: 1515
If I understood you correctly, you want 10 rows and 4 columns in your final list.
Test Data Preparation:
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
l2 = [x*10 for x in l1]
l3 = [x*100 for x in l1]
l4 = [x*1000 for x in l1]
Code you will need to write:
grid = [l1, l2, l3, l4]
trGrid = list(zip(*grid))
Testing:
for row in trGrid:
print(row)
Upvotes: 1