[Tutor] for loops over multiple lists of the same length
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? Emily ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] for loops over multiple lists of the same length
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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] for loops over multiple lists of the same length
+++ Emily Fortuna [22-06-06 13:22 -0400]: | 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? | Emily data = [['emily',6,'blue'],['jhon',34,'orange'],['jeremy',1,'green'],['junita',19,'yellow']] people = [Person(name,age,color) for name,age,color in data] Regards, Shantanoo -- Eliminate guilt. Don't fiddle expenses, taxes or benefits, and don't cheat colleagues. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor