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

前端 未结 3 551
伪装坚强ぢ
伪装坚强ぢ 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.

    0 讨论(0)
  • 2020-12-05 14:12

    Try

    result = ["_".join((i, j)) for i, j in itertools.izip(la, itertools.cycle(lb))]
    
    0 讨论(0)
  • 2020-12-05 14:32
    import itertools
    la = ['a1', 'a2', 'a3', 'a4']
    lb = ['b1', 'b2']
    for i, j in zip(la, itertools.cycle(lb)):
        print('_'.join((i,j)))
    
    0 讨论(0)
提交回复
热议问题