You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将单列表元素逐一添加到另一个列表的每个子列表中?

问题:将列表元素逐一添加到另一个列表的子列表中

现有两个列表:

list_1 = [[1,2],[3,4],[5,6],[7,8]]
list_2 = [11,12,13,14]

需要把list_2的元素逐一添加到list_1的对应子列表末尾,最终得到:

desired_output = [[1, 2, 11], [3, 4, 12], [5, 6, 13], [7, 8, 14]]

已尝试的方法

使用zip函数时得到了多余嵌套的结果,不符合需求:

list(zip(list_1,list_2))
# 输出:[((1, 2), 11), ((3, 4), 12), ((5, 6), 13), ((7, 8), 14)]

解决方案

方法1:列表推导式(推荐,生成新列表)

通过zip配对元素后,直接拼接子列表和单个元素的列表:

result = [sublist + [num] for sublist, num in zip(list_1, list_2)]
print(result)
# 输出:[[1, 2, 11], [3, 4, 12], [5, 6, 13], [7, 8, 14]]

这种方法会生成一个新列表,不会修改原有的list_1。

方法2:原地修改原列表

如果不需要保留原list_1的内容,可以直接遍历配对后的元素,用append添加:

for sublist, num in zip(list_1, list_2):
    sublist.append(num)
print(list_1)
# 输出:[[1, 2, 11], [3, 4, 12], [5, 6, 13], [7, 8, 14]]

方法3:使用map函数

用map结合lambda表达式实现简洁的转换:

result = list(map(lambda x, y: x + [y], list_1, list_2))
print(result)
# 输出:[[1, 2, 11], [3, 4, 12], [5, 6, 13], [7, 8, 14]]

内容的提问来源于stack exchange,提问作者Felipe D.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 05:53:17