Home  >  Q&A  >  body text

Python如何优雅的交错合并两个列表

比如a = [1, 2, 3], b = [4, 5, 6]
合并为[1, 4, 2, 5, 3, 6]
你觉得怎么写比较优雅?

伊谢尔伦伊谢尔伦2742 days ago1002

reply all(11)I'll reply

  • 黄舟

    黄舟2017-04-17 14:30:20

    pythonfrom itertools import chain
    list(chain.from_iterable(zip(a, b)))
    
    # py2
    list(chain(*zip(a, b)))
    

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 14:30:20

    Correction: There is a problem with the previous code, update it once.

    I don’t know if it’s elegant, but it should save memory:

    def xmerge(a, b):
        alen, blen = len(a), len(b)
        mlen = min(alen, blen)
        for i in xrange(mlen):
            yield a[i]
            yield b[i]
    
        if alen > blen:
            for i in xrange(mlen, alen):
                yield a[i]
        else:
            for i in xrange(mlen, blen):
                yield b[i]
    
    a = [1, 2, 3]
    b = [5, 6, 7, 8, 9, 10]
    
    c = [i for i in xmerge(a, b)]
    print c
    
    c = [i for i in xmerge(b, a)]
    print c
    

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 14:30:20

    It turns out that stackoverflow has already discussed it, and the writing method is very awkward. I personally love this:
    The cycle/islice functions called are all from itertools

    def roundrobin(*iterables):
        "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
        # Recipe credited to George Sakkis
        pending = len(iterables)
        nexts = cycle(iter(it).next for it in iterables)
        while pending:
            try:
                for next in nexts:
                    yield next()
            except StopIteration:
                pending -= 1
                nexts = cycle(islice(nexts, pending))
    

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 14:30:20

    pythondef xmerge(a, b):
      tmp = (list(a), list(b));
      return [tmp[i%2].pop(0) if tmp[i%2] else tmp[1-i%2].pop(0) for i in xrange(0, len(a) + len(b))]
    
    
    print xmerge([1,2,3], [5,6,7,8,9])
    print xmerge([1,2,3,4,5], [7,8,9])
    
    

    Is this so?

    //Halfway through writing, I searched for ternary expressions in python and remembered that I used python to feel like this kind of mythical beast flying by...
    //But there is also a language with three elements written as if a then b else c, which I can still understand now...

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 14:30:20

    python3.3
    result = [list(zip(a, b))[i][j] for i in range(len(a)) for j in range(len(list(zip(a, b))[0]))]
    
    虽然是一行,但是有点牵强,小括号太多
    

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 14:30:20

    python# Python 3
    def interpolate(*seqs):
        for items in zip(*seqs):
            yield from items
    
    >>> list(interpoltae('string', 'asdfgh'))
    ['s', 'a', 't', 's', 'r', 'd', 'i', 'f', 'n', 'g', 'g', 'h']
    

    There is a question, what should I do if these sequences are not all of equal length. The above solution is based on the smallest length:

    python>>> list(interpolate('string', 'asdf'))
    ['s', 'a', 't', 's', 'r', 'd', 'i', 'f']
    

    But what if you don’t choose the smallest one? Complementary characters? What characters should be added?

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 14:30:20

    For elegant data processing, scipy series libraries are still needed.
    There is a ready-made flatten function in matplotlib that can be used.

    from matplotlib.cbook import flatten
    a = [1, 2, 3]
    b = [4, 5, 6]
    list(flatten(zip(a,b)))
    

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 14:30:20

    a.extend(b)
    

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 14:30:20

    a = [1, 2, 3]
    b = [4, 5, 6]

    一般的方法

    def slove(a, b):
    c = []
    i = 0
    j = 0
    while i<len(a) and j<len(b):
    c.append(a[i])
    c.append(b[j])
    i += 1
    j += 1
    while i < len(a):
    c.append(a[i])
    i += 1
    while j < len(b):
    c.append(b[j])
    j += 1

    print(c)
    

    if name == 'main':
    slove(a, b)

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 14:30:20

    a=[1,2,3]
    b=[4,5,6]
    a=set(a)
    b=set(b)
    c=list(a|b)
    

    If it is just a merge of lists, can it be converted into set() and then the intersection operation
    Set is faster than list when doing list merge.
    But @lohocla4dam helped point out the shortcomings

    reply
    0
  • Cancelreply