猿问

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

有没有更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  output


mergePreserveOrder (list1 ,list2  )


沧海一幻觉
浏览 127回答 3
3回答

倚天杖

您可以zip一起使用chain.from_iterable:list(chain.from_iterable(zip(list1, list2)))示例:from itertools import chainlist1 = [['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]]

ABOUTYOU

只需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]]

qq_遁去的一_1

最通用的解决方案是模块roundrobin中的配方:itertoolsfrom itertools import cycle, islicedef 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将静默丢弃超出最短输入长度的所有元素。
随时随地看视频慕课网APP

相关分类

Python
我要回答