在python中查找对象内部列表的长度

时间:2014-10-12 02:12:49

标签: python list python-2.7

我试图编写一个使用len来查找列表长度的函数,该列表是python中对象的一个​​属性。

这是我的代码:

class Supplement(object):
    def __init__(self, name, price, ingredients, certifications):
        self.name = name
        self.price = price
        self.ingredients = ingredients
        self.certifications = certifications

    def print_certifications(self):
        print "The supplement %s has the following certifications:" % self.name
        for certification in self.certifications:
            if len(self.certifications) == 0:
                print "Sorry, no certifications for this product."
            else:
                print certification

UltimateProtein = Supplement("Ultimate Protein", 29.99, ["wheatgrass", "alfalfa grass",        
"probiotics"], ["organic", "vegan", "raw"])
UltimateFatLoss = Supplement("Ultimate Fat Loss", 39.99, ["lecithin", "chlorella", "spirulina"],         
[] )

UltimateProtein.print_certifications()
UltimateFatLoss.print_certifications()

当我执行程序时,我得到以下输出:

The supplement Ultimate Protein has the following certifications:
organic
vegan
raw

The supplement Ultimate Fat Loss has the following certifications:

我希望最后一行能够像这样阅读:

The supplement Ultimate Fat Loss has the following certifications:
Sorry, no certifications for this product.

什么阻止我的代码正确使用for循环?

1 个答案:

答案 0 :(得分:4)

因为没有为空列表执行for循环体。 (空列表;无需迭代)

检查for循环之外的长度。

def print_certifications(self):
    print "The supplement %s has the following certifications:" % self.name
    if not self.certifications:  # len(self.certifications) == 0
        print "Sorry, no certifications for this product."
    for certification in self.certifications:
        print certification