为了账号安全,请及时绑定邮箱和手机立即绑定

以 python 保留顺序合并两个或多个列表的最佳方法

以 python 保留顺序合并两个或多个列表的最佳方法

沧海一幻觉 2023-04-25 17:16:42
有没有更pythonic的方式来做到这一点?输入:list1 =  [['a',1],['b',2],['c',3],['d',4]]list2 =  [['e',5],['f',6],['g',7],['h',8]]期望的输出:out = [['a',1],['e',5],['b',2],['f',6],['c',3],['g',7],['d',4] ,['h',8]]我已经做好了:def mergePreserveOrder(*argv):          for arg in argv:          for arg2 in argv:             if(len(arg) != len(arg2)) :                print("arrays size do not match" + str(arg) +  str(arg2))                                return     output = []        for index in range (len(argv[0])):            for arg in argv:            output.append(arg[index])        return  outputmergePreserveOrder (list1 ,list2  )
查看完整描述

3 回答

?
倚天杖

TA贡献1828条经验 获得超3个赞

您可以zip一起使用chain.from_iterable

list(chain.from_iterable(zip(list1, list2)))

示例:


from itertools import chain


list1 = [['a',1],['b',2],['c',3],['d',4]]

list2 = [['e',5],['f',6],['g',7],['h',8]]


print(list(chain.from_iterable(zip(list1, list2))))

# [['a', 1], ['e', 5], ['b', 2], ['f', 6], ['c', 3], ['g', 7], ['d', 4], ['h', 8]]


查看完整回答
反对 回复 2023-04-25
?
ABOUTYOU

TA贡献1812条经验 获得超5个赞

只需itertools.chain使用zip

>>> import itertools

>>> list(itertools.chain(*zip(list1, list2)))

[['a', 1], ['e', 5], ['b', 2], ['f', 6], ['c', 3], ['g', 7], ['d', 4], ['h', 8]]


查看完整回答
反对 回复 2023-04-25
?
qq_遁去的一_1

TA贡献1725条经验 获得超7个赞

最通用的解决方案是模块roundrobin中的配方:itertools

from itertools import cycle, islice


def roundrobin(*iterables):

    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"

    # Recipe credited to George Sakkis

    num_active = len(iterables)

    nexts = cycle(iter(it).__next__ for it in iterables)

    while num_active:

        try:

            for next in nexts:

                yield next()

        except StopIteration:

            # Remove the iterator we just exhausted from the cycle.

            num_active -= 1

            nexts = cycle(islice(nexts, num_active))


list1 =  [['a',1],['b',2],['c',3],['d',4]]

list2 =  [['e',5],['f',6],['g',7],['h',8]]


print(list(roundrobin(list1, list2)))

产生你想要的输出。


chain与+不同zip,此解决方案适用于不均匀长度的输入,其中zip将静默丢弃超出最短输入长度的所有元素。


查看完整回答
反对 回复 2023-04-25
  • 3 回答
  • 0 关注
  • 91 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信