栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

以给定的合并顺序合并两个或多个列表

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

以给定的合并顺序合并两个或多个列表

您可以从这些列表创建迭代器,遍历排序列表,然后调用

next
其中一个迭代器:

i1 = iter(['a', 'b', 'c'])i2 = iter(['d', 'e'])# Select the iterator to advance: `i2` if `x` == 1, `i1` otherwiseprint([next(i2 if x else i1) for x in [0, 1, 0, 0, 1]]) # ['a', 'd', 'b', 'c', 'e']

可以将此解决方案推广到任意数量的列表,如下所示

def ordered_merge(lists, selector):    its = [iter(l) for l in lists]    for i in selector:        yield next(its[i])In [4]: list(ordered_merge([[3, 4], [1, 5], [2, 6]], [1, 2, 0, 0, 1, 2]))Out[4]: [1, 2, 3, 4, 5, 6]

如果排序列表包含字符串,浮点数或任何其他不能用作列表索引的对象,请使用字典:

def ordered_merge(mapping, selector):    its = {k: iter(v) for k, v in mapping.items()}    for i in selector:        yield next(its[i])In [6]: mapping = {'A': [3, 4], 'B': [1, 5], 'C': [2, 6]}In [7]: list(ordered_merge(mapping, ['B', 'C', 'A', 'A', 'B', 'C']))Out[7]: [1, 2, 3, 4, 5, 6]

当然,您也可以使用整数作为字典键。


或者,您可以从每个原始列表的左侧一一删除元素,然后将它们添加到结果列表中。快速示例:

In [8]: A = ['a', 'b', 'c']   ...: B = ['d', 'e']   ...: selector = [0, 1, 0, 0, 1]   ...:In [9]: [B.pop(0) if x else A.pop(0) for x in selector]Out[9]: ['a', 'd', 'b', 'c', 'e']

我希望第一种方法更有效(

list.pop(0)
)。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/647869.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号