Best way to do this? List loop (matrix?) iteration

Mitya Sirenef msirenef at lightbird.net
Wed Jan 9 01:33:18 CET 2013


On Tue 08 Jan 2013 07:19:59 PM EST, andydtaylor at gmail.com wrote:
> Hi!
>
> I might be missing the obvious, or I may have found something more complicated than the VBA I am used to. Could it be I need to use a maths library?
>
> For a given list of k items I'd like to turn it into an k*k matrix of item pairs.
>
> List_sample = ['a', 'b', 'c']
>
> Output:
>
> aa ab ac
> ba bb bc
> ca cb cc
>
> I'd like to have 2 hooks into this process
> 1. I want the opportunity to use a value pair each time they are generated (because I need to send these to an api and get a number back to put into a temporary list or dictionary - still tbd).
> 2. I'd also like to know each time a row is completed so I can bank that temporary list to a database table. Else build one big list and do it at the end, I'm still figuring this out.
>
> #Code I've tried:
>
>     stn_count = len(stn_list_short)
>     for rowcount in range (0, stn_count):
>        for colcount in range (0, stn_count):
>           print stn_list_long[rowcount] stn_list_long[colcount]
>
> I've found itertools, tee, and product and felt I was getting warmer. I'm still looking, but any pointers would be appreciated!
>
> Thanks,
>
> Andy
>
>


You can use itertools.product("abc", repeat=2) together with itertools 
recipe grouper() from the same page:

http://docs.python.org/3.3/library/itertools.html?highlight=itertools#itertools


HTH, -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/



More information about the Python-list mailing list