Oops, forgot to reply to the list; sorry everyone.

--
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.

--- Begin Message ---
Emily Fortuna wrote:

Thanks, I knew there had to be a really simple way to do it.
Emily


Orri Ganel wrote:

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?
Emily

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

>>> people = [Person(first_names[i], ages[i], colors[i]) for i in range(len(ages))]

Usually, you want to stay away from for i in range(len(foo)) because it's easier to just use for elem in foo or for i, elem in enumerate(foo), but since you need the indeces alone, this seems like an appropriate place to use it. Alternatively, you could zip them together:

>>> people = [Person(*zipped) for zipped in zip(first_names, ages, colors)]

By zipping the lists together, you end up with a list of three-tuples:

 >>> zip(first_names, ages, colors)
[('emily', 6, 'blue'), ('john', 34, 'orange'), ('jeremy', 1, 'green'), ('juanita', 19, 'yellow')]

And by putting an asterisk in front of zipped, you're passing each element in the three-tuple one at a time instead of the whole shebang at once, so that you end up with three arguments, not one.


HTH,
Orri



Actually, Kent had a very similar, and much more readable suggestion (if you didn't see it, it's the following):

>>> people = [Person(first_name, age, color) for first_name, age, color in zip(first_names, ages, colors)]

I guess it depends on how legible you feel your code needs to be; for some, my suggestion would be more than enough.

--
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.



--- End Message ---
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to