[Tutor] Nested for loops, possibly?

Bob Williams linux at barrowhillfarm.org.uk
Thu Feb 5 16:34:33 CET 2015


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On 05/02/15 13:57, Mark Lawrence wrote:
> 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:-
> 
Sometimes you have to shout, if the class won't listen ;-)

> for source in source_list: for sync in sync_list: do_sync(source,
> sync)
> 
Point taken, and understood.

> 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?
> 
Spot on! This is my first encounter with zip, but it does exactly what
I want here.

Many thanks

Bob
- -- 
Bob Williams
System:  Linux 3.16.7-7-desktop
Distro:  openSUSE 13.2 (x86_64) with KDE Development Platform: 4.14.3
Uptime:  06:00am up 7:55, 3 users, load average: 0.16, 0.05, 0.06
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2

iEYEARECAAYFAlTTjYYACgkQ0Sr7eZJrmU4HlQCeKPfXiSJEiR5D1JqeZkPLAfRn
AFMAoJhyCw75mC8b0+n8T6zIU0AnT0vM
=8NMM
-----END PGP SIGNATURE-----


More information about the Tutor mailing list