python - 通过放置一个列表中的第 n 个项目和另一个列表中的其他项目来合并 Python 中的列表?

标签 python list python-2.7 merge

我有两个列表,list1list2 .

这里 len(list2) << len(list1) .

现在我想合并这两个列表,使得最终列表的每个 第 n 个元素 来自 list2 来自list1 的其他人.

例如:

list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

list2 = ['x', 'y']

n = 3

现在最终的列表应该是:

['a', 'b', 'x', 'c', 'd', 'y', 'e', 'f', 'g', 'h']

什么是最Pythonic如何实现?

我想添加 list2 的所有元素到最终列表,最终列表应包括来自 list1 的所有元素和 list2 .

最佳答案

将较大的列表作为迭代器可以很容易地为较小列表的每个元素获取多个元素:

list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
list2 = ['x', 'y'] 
n = 3

iter1 = iter(list1)
res = []
for x in list2:
    res.extend([next(iter1) for _ in range(n - 1)])
    res.append(x)
res.extend(iter1)

>>> res
['a', 'b', 'x', 'c', 'd', 'y', 'e', 'f', 'g', 'h']

这避免了 insert ,这对于大型列表来说可能是昂贵的,因为每次都需要重新创建整个列表。

关于python - 通过放置一个列表中的第 n 个项目和另一个列表中的其他项目来合并 Python 中的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34692738/

相关文章:

Python句子反向器

python - 超过 1000 个主机的 pysnmp 扭曲客户端中的未处理错误

python - 为随机选择的变量分配一个值

java - 当两者的输出相同时,为什么我的 if/else 语句不匹配?

Python 2.7 无法从 urllib.request 中找到模块请求

sockets - 将 bytearray 与 socket.recv_into 一起使用

python - 从一个文件解析特定的 XML 属性并将其附加到另一个文件中,前提是第二个文件中存在另一个属性

python - 如何在python中获取最大堆

python - linux合并picard中的多个文件

python - 删除列表中 2 个重复的交换子列表