Pythonic way to combine two lists in an alternating fashion?

前端 未结 21 3091
误落风尘
误落风尘 2020-11-22 16:13

I have two lists, the first of which is guaranteed to contain exactly one more item than the second. I would like to know the most Pythonic way to create a

相关标签:
21条回答
  • 2020-11-22 17:08

    Might be a bit late buy yet another python one-liner. This works when the two lists have equal or unequal size. One thing worth nothing is it will modify a and b. If it's an issue, you need to use other solutions.

    a = ['f', 'o', 'o']
    b = ['hello', 'world']
    sum([[a.pop(0), b.pop(0)] for i in range(min(len(a), len(b)))],[])+a+b
    ['f', 'hello', 'o', 'world', 'o']
    
    0 讨论(0)
  • 2020-11-22 17:10

    This one is based on Carlos Valiente's contribution above with an option to alternate groups of multiple items and make sure that all items are present in the output :

    A=["a","b","c","d"]
    B=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
    
    def cyclemix(xs, ys, n=1):
        for p in range(0,int((len(ys)+len(xs))/n)):
            for g in range(0,min(len(ys),n)):
                yield ys[0]
                ys.append(ys.pop(0))
            for g in range(0,min(len(xs),n)):
                yield xs[0]
                xs.append(xs.pop(0))
    
    print [x for x in cyclemix(A, B, 3)]
    

    This will interlace lists A and B by groups of 3 values each:

    ['a', 'b', 'c', 1, 2, 3, 'd', 'a', 'b', 4, 5, 6, 'c', 'd', 'a', 7, 8, 9, 'b', 'c', 'd', 10, 11, 12, 'a', 'b', 'c', 13, 14, 15]
    
    0 讨论(0)
  • 2020-11-22 17:11

    Multiple one-liners inspired by answers to another question:

    import itertools
    
    list(itertools.chain.from_iterable(itertools.izip_longest(list1, list2, fillvalue=object)))[:-1]
    
    [i for l in itertools.izip_longest(list1, list2, fillvalue=object) for i in l if i is not object]
    
    [item for sublist in map(None, list1, list2) for item in sublist][:-1]
    
    0 讨论(0)
提交回复
热议问题