Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

loops

list

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:

la = ['a1', 'a2', 'a3', 'a4'] lb = ['b1', 'b2'] result = ['a1_b1', 'a2_b2', 'a3_b1', 'a4_b2'] 

I have a list of dates and some of them have something marked on them. I then have a much larger list of dates and I want to put the smallest list inside the bigger list as many times as possible. It will probably require some sort of loop as I need access to the dates in the larger list for the end result.

For some reason, I just cannot see a good way to do this.

like image 716
Mathias Nielsen Avatar asked Jan 27 '11 11:01

Mathias Nielsen


People also ask

How do I loop through two lists at the same time?

Use zip() and a for-loop to iterate over two lists Call zip(iter1 iter2) to create an iterator that aggregates corresponding elements from lists iter1 and iter2 together. Use a for-loop to iterate over this iterator, stopping at the length of the shorter list.

How do I iterate two lists at the same time in python?

Use the izip() Function to Iterate Over Two Lists in Python It iterates over the lists until the smallest of them gets exhausted. It then zips or maps the elements of both lists together and returns an iterator object. It returns the elements of both lists mapped together according to their index.


1 Answers

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.

like image 62
snakile Avatar answered Oct 13 '22 11:10

snakile