通过将一个列表中的每个第n个项目与另一个列表中的其他项放置在一起来合并Python中的列表? [英] Merge lists in Python by placing every nth item from one list and others from another?

查看:29
本文介绍了通过将一个列表中的每个第n个项目与另一个列表中的其他项放置在一起来合并Python中的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表, list1 list2 .

此处 len(list2)<<len(list1) .

Here len(list2) << len(list1).

现在,我想合并两个列表,以使最终列表的每个 nth元素分别来自 list2 其他列表来自 list1 .

Now I want to merge both of the lists such that every nth element of final list is from list2 and the others from 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 中的所有元素.

I want to add all elements of list2 to the final list, final list should include all elements from list1 and list2.

推荐答案

使较大的列表成为迭代器,可以轻松地为较小的列表的每个元素采用多个元素:

Making the larger list an iterator makes it easy to take multiple elements for each element of the smaller list:

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 (对于大型列表而言这可能是昂贵的,因为每次都需要重新创建整个列表).

This avoids insert which can be expensive for large lists because each time the whole list needs to be re-created.

这篇关于通过将一个列表中的每个第n个项目与另一个列表中的其他项放置在一起来合并Python中的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆