Pythonic way to combine two lists in an alternating fashion?

前端 未结 21 3348
误落风尘
误落风尘 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: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]
    

提交回复
热议问题