[Tutor] redundant function ( or, I need advice about cleaning up my code )

Max Noel maxnoel_fr at yahoo.fr
Sun Oct 31 03:47:38 CET 2004


On Oct 31, 2004, at 02:23, Morgan Meader wrote:

> Anyway... I thank you and will look into the areas you suggested... 
> esp. List comprehension and foreach.
>
> Question:
> I did it that way because I had more than one list I was looking at. 
> Is there another way to have the index so I can get values that match 
> up by index on multiple lists?

	Mmh... I don't think there's a built-in way to do that, but you can 
create a custom iterator that will do the job. (iterators are another 
great thing in Python, Ruby and Java)



def multiList(what):
     """Iterates over multiple lists at the same time. what is a list of
     lists of thesame size, and the function yields a series of tuples,
     where the i-th tuple yielded contains the i-th element
     in each list in what."""

     for i in range(len(what[0])):
         # This is exactly what I was warning you against.
         # There has to be a better way of doing this,
         # only I can't seem to be able to find it. D'oh!
         out = [element[i] for element in what]
         yield tuple(out)



	Then, you just use a for loop that looks like this:

for (gROWname, gROWtype) in multiList((job.matrix.info['gROWname'], 
job.matrix.info['gROWtype'])):
	# do stuff


	Warning, my code here is quick & dirty, and untested. Use at your own 
risk. But anyway, you get the idea. ^^

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"



More information about the Tutor mailing list