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

如何将ListA对应元素插入ListB子列表的元素间及末尾?

问题解决:在列表子元素间及末尾插入对应元素

需求说明

将ListA中的对应元素,插入到ListB各子列表的每两个元素之间,同时添加到子列表的末尾。

输入示例

ListA = ["A", "B"]
ListB = [[1, 2, 3, 4], [5, 6, 7, 8]]

期望输出

[[1, 'A', 2, 'A', 3, 'A', 4, 'A'], [5, 'B', 6, 'B', 7, 'B', 8, 'B']]

现有代码的问题

当前实现仅能将ListA元素添加到子列表末尾,无法插入到元素之间:

for x, y in zip(ListB, ListA):
    x.append(y)

对应输出:

[[1, 2, 3, 4, 'A'], [5, 6, 7, 8, 'B']]

解决方案

方法1:循环构建新列表(直观易懂)

遍历每组子列表和对应标记元素,逐个将数字和标记交替添加到新列表中:

result = []
for sublist, val in zip(ListB, ListA):
    new_sublist = []
    for num in sublist:
        new_sublist.append(num)
        new_sublist.append(val)
    result.append(new_sublist)

方法2:列表推导式(简洁高效)

利用zip将子列表元素与重复的标记元素配对,再展开成新列表:

result = [[item for pair in zip(sublist, [val]*len(sublist)) for item in pair] 
          for sublist, val in zip(ListB, ListA)]

两种方法都能得到符合要求的输出,第一种逻辑清晰适合新手,第二种代码简洁适合追求效率的场景。

内容的提问来源于stack exchange,提问作者Tanwir Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 08:45:31