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)?
[Ingredient(*ing) for ing in ings]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With