Merging two lists in a certain format in Python
Question:
I have two lists A
and B
. I am trying to merge the two lists into one in a specific format as shown in the expected output. I also show the current output.
A=[0, 1]
B=[[1,2],[3,4]]
C=A+B
print(C)
The current output is
[0, 1, [1, 2], [3, 4]]
The expected output is
[[0, 1, 2], [1, 3, 4]]
Answers:
lst=[]
for x, y in zip(A, B):
lst.append([x] + y)
#[[0, 1, 2], [1, 3, 4]]
Or as @Mechanic Pig suggested in comments using list comprehension:
[[a] + b for a, b in zip(A, B)]
You can also use np.insert
:
a = np.array([0, 1])
b = np.array([[1, 2], [3, 4]])
np.insert(b, 0, a, axis=1)
A=[0, 1]
B=[[1,2],[3,4]]
c=[]
for i in range(len(A)):
c.append([A[i]])
for j in range(len(B[i])):
c[i].append(B[i][j])
print(c)
[[0, 1, 2], [1, 3, 4]]
I have two lists A
and B
. I am trying to merge the two lists into one in a specific format as shown in the expected output. I also show the current output.
A=[0, 1]
B=[[1,2],[3,4]]
C=A+B
print(C)
The current output is
[0, 1, [1, 2], [3, 4]]
The expected output is
[[0, 1, 2], [1, 3, 4]]
lst=[]
for x, y in zip(A, B):
lst.append([x] + y)
#[[0, 1, 2], [1, 3, 4]]
Or as @Mechanic Pig suggested in comments using list comprehension:
[[a] + b for a, b in zip(A, B)]
You can also use np.insert
:
a = np.array([0, 1])
b = np.array([[1, 2], [3, 4]])
np.insert(b, 0, a, axis=1)
A=[0, 1]
B=[[1,2],[3,4]]
c=[]
for i in range(len(A)):
c.append([A[i]])
for j in range(len(B[i])):
c[i].append(B[i][j])
print(c)
[[0, 1, 2], [1, 3, 4]]