Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating a list with objects using list comprehension expression

I am trying to populate a list of 8 Ingredient objects using one list comprehension expression. The code looks like that:

import random
ings = (('w1', 200, 25, 80),
   ('su1', 50, 55, 150),
   ('su2', 400, 100, 203),
   ('sy1', 10, 150, 355),
   ('sy2', 123, 88, 101),
   ('sy3', 225, 5, 30),
   ('sy4', 1, 44, 99),
   ('sy5', 500, 220, 300),)

class Ingredient: 
    def __init__(self, n, p, mi, ma):
        self.name = n
        self.price = p
        self.min = mi
        self.max = ma
        self.perc = random.randrange(mi, ma)

class Drink:
    def __init__(self): 
        self.ing = []

and i would like to obtain result equivalent to this:

self.ing = [Ingredient('w1', 200, 25, 80), Ingredient('su1', 50, 55, 150) ... 
(and so it goes for the ings tuple) ]

Now, my question is how to do it using LCE or if there is more optimal way of doing this (in terms of code readability or speed)?

like image 243
kyooryu Avatar asked Nov 05 '11 00:11

kyooryu


1 Answers

[Ingredient(*ing) for ing in ings]
like image 102
yosukesabai Avatar answered Oct 26 '22 15:10

yosukesabai