如何将一个列表中的每个项目附加到另一个列表的每个子列表中?
a = [['a','b','c'],['d','e','f'],['g','h','i']]
b = [1,2,3]
结果应该是:
[['a','b','c',1],['d','e','f',2],['g','h','i',3]]
请记住,我希望将此项列入一个非常大的列表,因此效率和速度非常重要。
我试过了:
for sublist,value in a,b:
sublist.append(value)
它返回'ValueError:解压缩的值太多'
也许listindex或listiterator可以工作,但不知道如何在这里申请
答案 0 :(得分:4)
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)
结果:
>>> a
[['a', 'b', 'c', 1], ['d', 'e', 'f', 2], ['g', 'h', 'i', 3]]
原始解决方案不起作用的原因是,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)]
答案 1 :(得分:1)
这是一个简单的解决方案:
a = [['a','b','c'],['d','e','f'],['g','h','i']]
b = [1,2,3]
for i in range(len(a)):
a[i].append(b[i])
print(a)
答案 2 :(得分:0)
使用列表理解的一个选项:
a = [(a[i] + b[i]) for i in range(len(a))]
答案 3 :(得分:0)
只需遍历子列表,一次添加一个项目:
for i in range(0,len(listA)):
listA.append(listB[i])
答案 4 :(得分:0)
你可以这样做:
>>> a = [['a','b','c'],['d','e','f'],['g','h','i']]
>>> b = [1,2,3]
>>> [l1+[l2] for l1, l2 in zip(a,b)]
[['a', 'b', 'c', 1], ['d', 'e', 'f', 2], ['g', 'h', 'i', 3]]
您还可以滥用列表推导的副作用来完成此任务:
>>> [l1.append(l2) for l1, l2 in zip(a,b)]
[None, None, None]
>>> a
[['a', 'b', 'c', 1], ['d', 'e', 'f', 2], ['g', 'h', 'i', 3]]