Coding Nested Loops

George Sakkis george.sakkis at gmail.com
Fri Sep 15 16:38:31 EDT 2006


Peter Otten wrote:

> from itertools import count, izip, cycle, chain, repeat, starmap, imap
> from random import choice
>
> first =  ["X", "Y", "Z"]
> second = ["A", "B", "C"]
> second_count = [13, 14, 33]
> third = [1.1, 2.2, 3.3, 4.4]
>
> random_floats = imap(choice, repeat(third))
> columns = [
>     count(),
>     chain(*[repeat(i, 60) for i in first]),
>     cycle(chain(*starmap(repeat, izip(second, second_count))))
> ]
> columns.extend(repeat(random_floats, 28))
>
> for row in izip(*columns):
>     print row
>
> Now that is a nice occasion to get acquainted with the itertools module...

Wow, that's the most comprehensive example of itertools (ab)use I have
seen! Awesome!

George




More information about the Python-list mailing list