将一个列表的项目插入到另一个列表

时间:2019-08-18 17:56:51

标签: python-3.x list indexing addition

我想加入以下形式的两个列表:

a=[[[1,2,3],[4,5,6],[7,8,9]],[[11,21,31],[14,15,16],[17,18,19]],[[41,42,43],[48,45,46],[76,86,96]]]
b=[[55,66,99],[77,88,44],[100,101,100]]

结果是:

result =[[[55,1,2,3],[66,4,5,6],[99,7,8,9]],[[77,11,21,31],[88,14,15,16],[44,17,18,19]],[[100,41,42,43],[101,48,45,46],[100,76,86,96]]]

我尝试这样做,但是不起作用

for i in range(len(a)): 
    for j in range(len(a[i])):
        a[i][j].insert(0, b[i][j])

a

2 个答案:

答案 0 :(得分:0)

尝试此代码:

a=[[[1,2,3],[4,5,6],[7,8,9]],[[11,21,31],[14,15,16],[17,18,19]],[[41,42,43],[48,45,46],[76,86,96]]]
b=[[55,66,99],[77,88,44],[100,101,100]]
for i in range(0,3):
    for j in range(0,3):
        result = a[i][j]
        result.insert(0, b[i][j])
        print(result)

答案 1 :(得分:0)

首先,我建议不要更改要迭代的可迭代对象。 您可以在Modifying list while iterating上阅读更多内容。

第二,我想提出使用带有 function Export() { queryGroup = fields(); const response = async.map(queryGroup, a=>ApiCall(a), function(err, results) { return results; }); return response; } async function ApiCall(lookup) { console.log("LOOKUP: " + JSON.stringify(lookup)); var table = new Object(); superagent .get(document.getElementById("ApiEndPoint").value+'/api/'+document.getElementById("ApiKey").value+'/'+lookup.title) .query(lookup.content) .set('accept', 'json') .then(res => { table["Body"] = res.body table["Name"] = lookup.title; console.log("completed: "+ lookup.title); return table; }).then(table => {return Promise.resolve(table);}); } 函数的嵌套循环作为解决方案:

zip

外部循环遍历a = [[[1,2,3],[4,5,6],[7,8,9]],[[11,21,31],[14,15,16],[17,18,19]],[[41,42,43],[48,45,46],[76,86,96]]] b = [[55,66,99],[77,88,44],[100,101,100]] c = [] for i, j in zip(a, b): for k, m in zip(i, j): c.append([m] + k) # k.insert(0, m) if you want to change k in-place (not recommended) 中的第一级嵌套列表和a中的列表。内部循环遍历b中的第二级列表和a中的整数。这些值将合并到单个b中,并将附加到list上。

您可以在https://docs.python.org/3/library/functions.html#zip上详细了解c函数。