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

本秂侑毒 提交于 2019-11-29 05:29:59

Try

result = ["_".join((i, j)) for i, j in itertools.izip(la, itertools.cycle(lb))]

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!