使用列表推导表达式使用对象填充列表

时间:2011-11-05 00:29:18

标签: python list-comprehension

我正在尝试使用一个列表推导表达式填充8个Ingredient对象的列表。 代码看起来像这样:

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 = []

我希望获得与此相当的结果:

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

现在,我的问题是如何使用LCE或者如果有更好的方法(在代码可读性或速度方面)?

3 个答案:

答案 0 :(得分:7)

[Ingredient(*ing) for ing in ings]

答案 1 :(得分:1)

您应该直接创建Ingredient实例,而不是定义元组然后转换它们:

import random

class Ingredient: 
    def __init__(self, name, price, min, max):
        self.name = name
        self.price = price
        self.min = min
        self.max = max

        self.perc = random.randrange(self.min, self.max)

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

答案 2 :(得分:0)

self.ing = [Ingredient(*options) for options in ings]