如何从不同的列表中向特定列表插入不同的值

时间:2021-02-15 07:56:06

I have a list

我有一份清单

a = [[1,2,3],[3,4,5]]

In every row at the end I want to insert values from a different list

在最后的每一行中,我想插入来自不同列表的值

b=[6,7]

I want the results to be

我想要结果

[[1,2,3,6],[3,4,5,7]]

I am using:

我在用:

for i in range (0,len(a)):
    for j in range (0,len(b)):
        if j==0:
            a[i].append(b[j])
            m.append(a[i])
        else:
            a[i][3]=b[j]
            m.append(a[i])
        print m

But I am not getting the expected results. This gives me:

但我没有得到预期的结果。这给了我:

[[1, 2, 3, 7], [1, 2, 3, 7], [3, 4, 5, 7], [3, 4, 5, 7]]

Could someone help me out with the correct code snippet.

有人可以用正确的代码片段帮助我。

2 个解决方案

#1


1  

Using zip

Ex:

a=[[1,2,3],[3,4,5]]
b=[6,7]

for i, j in zip(a,b):
    i.append(j)
print(a)

Output:

[[1, 2, 3, 6], [3, 4, 5, 7]]

#2


2  

Here is a solution using zip:

这是一个使用zip的解决方案:

result = [sublist_a + [el_b] for sublist_a, el_b in zip(a, b)]

which gives the expected output:

它给出了预期的输出:

[[1, 2, 3, 6], [3, 4, 5, 7]]

#1


1  

Using zip

Ex:

a=[[1,2,3],[3,4,5]]
b=[6,7]

for i, j in zip(a,b):
    i.append(j)
print(a)

Output:

[[1, 2, 3, 6], [3, 4, 5, 7]]

#2


2  

Here is a solution using zip:

这是一个使用zip的解决方案:

result = [sublist_a + [el_b] for sublist_a, el_b in zip(a, b)]

which gives the expected output:

它给出了预期的输出:

[[1, 2, 3, 6], [3, 4, 5, 7]]