Reputation: 5117
Let's suppose that I have 3 python two-dimensional lists (data_1
, data_2
, data_3
) of 10x5 dimensions. I want to make one list (all_data
) from them with 30x5 dimensions. For now, I am doing this by applying the following:
data_1 = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], ..., [46, 47, 48, 49, 50]]
data_2 = [[101, 102, 103, 104, 105], [106, 107, 108, 109, 110], ..., [146, 147, 148, 149, 150]]
data_3 = [[201, 202, 203, 204, 205], [206, 207, 208, 209, 210], ..., [246, 247, 248, 249, 250]]
all_data = []
for index, item in enumerate(data_1):
all_data.append(item)
for index, item in enumerate(data_2):
all_data.append(item)
for index, item in enumerate(data_3):
all_data.append(item)
If I simply do something like this:
all_data.append(data_1)
all_data.append(data_2)
all_data.append(data_3)
then I get a list of 3x10x5 which is not what I want.
So can I create a 30x5 list by appending three 10x5 lists without using any for loop?
Upvotes: 1
Views: 4530
Reputation: 344
Simply write:
all_data = data_1 + data_2 + data_3
If you want to merge all the corresponding sublists of these lists, you can write:
# function that merges all sublists in single list
def flatten(l):
return [el for subl in l for el in subl]
# zipped - is a list of tuples of corresponding items (our deep sublists) of all the lists
zipped = zip(data_1, data_3, data_3)
# merge tuples to get single list of rearranges sublists
all_data = flatten(zipped)
Upvotes: 5
Reputation: 800
You can just extend
your list.
data = []
data.extend(d1)
data.extend(d2)
data.extend(d3)
Upvotes: 7
Reputation: 10146
In case you don't mind it being lazy, you could also do
import itertools
all_data = itertools.chain(data1, data2, data3)
Upvotes: 0
Reputation: 20590
This should work:
data=[]
data[len(data):] = data1
data[len(data):] = data2
data[len(data):] = data3
Upvotes: 0