将值列表附加到子列表

Chr*_*ris 3 python iteration iterator list sublist

如何将一个列表的每个项目附加到另一个列表的每个子列表?

a = [['a','b','c'],['d','e','f'],['g','h','i']]
b = [1,2,3]
Run Code Online (Sandbox Code Playgroud)

结果应该是:

[['a','b','c',1],['d','e','f',2],['g','h','i',3]]
Run Code Online (Sandbox Code Playgroud)

请记住,我想对一个非常大的列表执行此操作,因此效率和速度很重要。

我试过了:

for sublist,value in a,b:
    sublist.append(value)
Run Code Online (Sandbox Code Playgroud)

它返回“ValueError:要解压的值太多”

也许 listindex 或 listiterator 可以工作,但不知道如何在这里应用

Aka*_*all 5

a = [['a','b','c'],['d','e','f'],['g','h','i']]            
b = [1,2,3]

for ele_a, ele_b in zip(a, b):
    ele_a.append(ele_b)
Run Code Online (Sandbox Code Playgroud)

结果:

>>> a
[['a', 'b', 'c', 1], ['d', 'e', 'f', 2], ['g', 'h', 'i', 3]]
Run Code Online (Sandbox Code Playgroud)

您的原始解决方案不起作用的原因是它a,b确实创建了一个tuple,但不是您想要的。

>>> z = a,b
>>> type(z)
<type 'tuple'>
>>> z
([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']], [1, 2, 3])
>>> len(z[0])
3
>>> for ele in z:
...    print ele
... 
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] #In your original code, you are
[1, 2, 3]                                           #unpacking a list of 3 elements 
                                                    #into two values, hence the 
                                                    #'ValueError: too many values to unpack'

>>> zip(a,b)  # using zip gives you what you want.
[(['a', 'b', 'c'], 1), (['d', 'e', 'f'], 2), (['g', 'h', 'i'], 3)]
Run Code Online (Sandbox Code Playgroud)