[Tutor] for loops over multiple lists of the same length
Kent Johnson
kent37 at tds.net
Thu Jun 22 19:39:04 CEST 2006
Emily Fortuna wrote:
> I feel like there should be a better way to do this process:
> Can you please help?
> (This is trivial example code I created off the top of my head, but the
> same concept that I am trying to do elsewhere.)
>
> class Person(object):
> def __init__(self, first_name, age, fav_color):
> self.first_name = first_name
> self.age = age
> self.fav_color = fav_color
>
> first_names = ['emily', 'john', 'jeremy', 'juanita']
> ages = [6, 34, 1, 19]
> colors = ['blue', 'orange', 'green', 'yellow']
>
> ageIter = ages.iter()
> colorIter = colors.iter()
> people = [Person(name, ageIter.next(), colorIter.next()) for name in
> first_names]
>
> print people
>
> any suggestions, please?
The builtin function zip() does this:
people = [Person(name, age, color) for name, age color in
zip(first_names, ages, colors)]
Kent
More information about the Tutor
mailing list