[Tutor] Nested for loops, possibly?
Mark Lawrence
breamoreboy at yahoo.co.uk
Thu Feb 5 14:57:56 CET 2015
On 05/02/2015 13:27, Bob Williams wrote:
>
> I would like to reduce all those repeated calls to do_sync() in main(), for example, to one by putting the *_srcpath and *_*syncpath variables into lists (eg. source_list and sync_list) and using a for loop to get the first item out of each list, then the second item, etc. Something like:
>
> for i in range(0, len(source_list)):
> for j in range(0, len(sync_list)):
> do_sync(source_list[i], sync_list[j])
>
> but this will get all the values of sync_list[j] for each value of source_list[i], which is not what I want.
>
> I hope this is clear enough to see my problem? I realise that the print statements will need some work, I'm just trying to get the functionality working.
>
> TIA
>
> Bob
>
Apologies for shouting but this has been said several times in the past
so I'm deliberately emphasising the point. YOU *DON'T* NEED TO LOOP
THROUGH ITEMS IN A LIST USING range AND len. Hence:-
for source in source_list:
for sync in sync_list:
do_sync(source, sync)
Having said that I haven't looked at your code in depth, but I think
you're looking for something like:-
for source, sync in zip(source_list, sync_list):
do_sync(source, sync)
Let's try it.
>>> def do_sync(source, sync):
... print('Source is', source, 'Sync is', sync)
...
>>> source_list = ['a', 'b', 'c']
>>> sync_list = ['w', 'x', 'y']
>>> for source, sync in zip(source_list, sync_list):
... do_sync(source, sync)
...
Source is a Sync is w
Source is b Sync is x
Source is c Sync is y
Am I close?
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Tutor
mailing list