【问题标题】:Best way to merge two or more list in python preserving order [duplicate]以python保留顺序合并两个或多个列表的最佳方法[重复]
【发布时间】:2020-08-05 04:08:01
【问题描述】:

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

【问题讨论】:

    标签: python python-3.x merge


    【解决方案1】:

    您可以将zipchain.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]]
    

    【讨论】:

      【解决方案2】:

      只需将itertools.chainzip 一起使用:

      >>> import itertools
      >>> list(itertools.chain(*zip(list1, list2)))
      [['a', 1], ['e', 5], ['b', 2], ['f', 6], ['c', 3], ['g', 7], ['d', 4], ['h', 8]]
      

      【讨论】:

        【解决方案3】:

        最通用的解决方案是来自the itertools moduleroundrobin 配方:

        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 将静默丢弃超出最短输入长度的所有元素。

        【讨论】:

          猜你喜欢
          • 2015-07-15
          • 2016-09-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-28
          • 2011-03-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多