Loop over 2 lists, repeating the shortest until end of longest

前端 未结 3 570
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 13:37

I am sure there is an easy and obvious way to do this, but I have been googling and reading the docs and I just cannot find anything.

This is what I want to achieve:

3条回答
  •  一个人的身影
    2020-12-05 14:06

    Assuming la is longer than lb:

    >>> import itertools
    >>> [x+'_'+y for x,y in zip(la, itertools.cycle(lb))]
    ['a1_b1', 'a2_b2', 'a3_b1', 'a4_b2']
    
    • itertools.cycle(lb) returns a cyclic iterator for the elements in lb.

    • zip(...) returns a list of tuples in which each element corresponds to an element in la coupled with the matching element in the iterator.

提交回复
热议问题