Home > Enterprise >  How to combine two list into one list?
How to combine two list into one list?

Time:06-20

I have two list, and want to combine the two in one nested list, with comma separate them

list A

[[1,1],[1,2],[1,3]]

list B

[[2,1],[2,2],[2,3]]

Expected output is:

[
[[1,1],[2,1]],
[[1,2],[2,2]],
[[1,3],[2,3]]
[

CodePudding user response:

Iterate two list by zip

a = [[1,1],[1,2],[1,3]]
b = [[2,1],[2,2],[2,3]]


c = [[i, j] for i, j in zip(a, b)]
print(c)  # [[[1, 1], [2, 1]], [[1, 2], [2, 2]], [[1, 3], [2, 3]]]

CodePudding user response:

You can also use map with zip

a = [[1,1],[1,2],[1,3]]
b = [[2,1],[2,2],[2,3]]
map(list, zip(a,b))

CodePudding user response:

I get a stupid for loop method:

c = []

#[[[1,3548],[2,2729]],]
for i in range(len(a)):
    for j in range(len(b)):
        if i == j:
            c.append([a[i],b[j]])

It seems to work.

  • Related