Let's say I have:
A = [[a,b,c,d],[1,2,3,4]]
B = [[1.2,1.7],[1.6,1.8]]
I want to combine 2 list to one list
C = [[a,b,c,d,1.2,1.7],[1,2,3,4,1.6,1.8]]
How can I do that in Python? Thanks
Let's say I have:
A = [[a,b,c,d],[1,2,3,4]]
B = [[1.2,1.7],[1.6,1.8]]
I want to combine 2 list to one list
C = [[a,b,c,d,1.2,1.7],[1,2,3,4,1.6,1.8]]
How can I do that in Python? Thanks
Use extend()
method to concatenate the elements of one list to another and then append this resulting list to the final list.
for i in range(len(a)):
a[i].extend(b[i])
c.append(a[i])
There are lot's of different ways of combining two lists.
You can add two lists together:
[1,2,3] + [4,5,6]
Will give you:
[1,2,3,4,5,6]
You can append a list to a list of lists:
[[1,2,3],[4,5,6]].append([7,8,9])
Will give you:
[[1,2,3],[4,5,6],[7,8,9]]
You can zip two lists as well:
zip([1,2,3],[4,5,6])
Will give you:
[(1,4),(2,5),(3,6)]
What it looks like you're looking for is:
C = []
for sublist_1, sublist_2 in zip(A, B):
C.append(sublist_1 + sublist_2)
Or more compactly using list comprehension:
C = [sublist_1 + sublist_2 for sublist_2, sublist_2 in zip(A,B)]
You can use zip
and itertools.starmap
for this
In [110]: A
Out[110]: [[2, 4, 5, 6], [1, 2, 3, 4]]
In [111]: B
Out[111]: [[1.2, 1.7], [1.6, 1.8]]
In [112]: import itertools
In [113]: list(itertools.starmap(lambda x,y:x+y,zip(A,B)))
Out[113]: [[2, 4, 5, 6, 1.2, 1.7], [1, 2, 3, 4, 1.6, 1.8]]