python - 将值列表附加到子列表

标签 python list iterator iteration sublist

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

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 可以工作,但不确定如何在这里应用

最佳答案

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)]

关于python - 将值列表附加到子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21323272/

相关文章:

python - Django 区域数据 MultiPolygonField

python在多维字典中使用函数

android - 简单的 XML ElementListUnion - 不允许两个通用列表?

list - 对Prolog中的列表进行排序

c++ - 遍历 unordered_map C++

python - 带有 spacy 的自定义 POS 标记

python - 使用 python NLTK : How can I improve the accuracy of the POS tagger?

python - 如何对句子列表进行词形还原

arrays - 如何最好地返回固定大小的数组,而无需创建具有虚拟值或手动展开的数组?

java - 连续对象值提取器的设计模式