列出理解python?

2024-04-25 22:47:22 发布

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

我有这样一个函数:

  for product in responseSoup.findAll("offersummary"):
        try:
            if product.lowestnewprice.formattedprice != None:
                price.append(product.lowestnewprice.formattedprice.text)
            else:
                price.append("")
        except:
            price.append("")

我不知道如何用try/except块执行if/else语句?列表理解能提高效率吗?你知道吗

   [product.lowestnewprice.formattedprice for product in responseSoup.findAll("offersummary")]  

Tags: 函数inforifproductpriceelsetry
2条回答

tryexcept块用于查看以下代码是否有效。如果不是,并且它与给定的错误匹配,则运行该代码块。否则,运行另一行代码。例如:

try:
    m = raw_input("Please enter an integer")
    n = int(m)
except ValueError:
    print "Invalid number"
else:
    print n

因此,程序试图分配m来自用户的输入。然后n将输入赋值为整数。现在选择的错误是ValueError,因为如果m是一个字符串,那么转换为n将引发该错误。如果是这样,那么它将执行except块中的代码,即打印“无效数字”。如果转换成功,则打印n。你知道吗

现在使用您的程序,您将尝试ifelse块。如果代码不工作并且引发了except块中给出的错误,它将执行price.append("")。否则,它将运行else块中的代码,而您没有。您需要else:try/except块中工作,这样它才能在except语句中的关键字except之后包含指定的错误。你知道吗

下面是一个非常可读的解决方案:

prices = []
for product in responseSoup.findAll("offersummary"):
    price = product.get(lowestnewprice, {}).get(formattedprice, {}).get(text)
    if price is not None:
        prices.append(price)        
    else:
        prices.append('')

如果你真的不在乎可读性,这里有一个看起来非常糟糕的单行线:

price = [''
         if product.get(lowestnewprice, {}).get(formattedprice, {}).get(
             text) is None else
         product.lowestnewprice.formattedprice.text
         for product in responseSoup.findAll("offersummary")]

它们基本上做相同的事情,但是,在我看来,更具可读性的解决方案更好。你知道吗

编辑

我刚刚想出了一个更好的一行:

price = [product.get(lowestnewprice,{}).get(formattedprice,{}).get(text) or ''
         for product in responseSoup.findAll("offersummary")]

它的可读性仍然不如“非常可读”的解决方案,但也不算太差。现在这个决定真的取决于你的喜好。你知道吗

相关问题 更多 >