Python中查找对象内列表的长度

2024-06-16 12:24:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个函数,它使用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()

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

^{pr2}$

我希望最后一行是这样写的:

^{3}$

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


Tags: 代码nameself列表forlendefprice
1条回答
网友
1楼 · 发布于 2024-06-16 12:24:46

因为没有对空列表执行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

相关问题 更多 >