简体   繁体   English

在python中,我应该使用try还是If和为什么?

[英]In python should I use try or If and why?

First of all, I know the difference between if and try and I am perfectly aware that their purposes are completely different -while one makes tests, the other manages errors. 首先,我知道if和try之间的区别,并且我完全意识到它们的用途是完全不同的-一个进行测试,另一个进行错误处理。 However, in this particular case, is it better to use if or try ? 但是,在这种情况下,最好使用if或try吗?

#option1
def getListRank(self):
    for point in self.soup.findAll('td',class_="rank-cell"):
        p = (point.get_text().replace('\t','').replace('\n','')
                             .replace('\r','').replace(',',''))
        if 'T' in p:
            self.listRk.append(int(p.replace('T',''))
        else:
            self.listRk.append(int(p))
    return self.listRk 

I am very tempted to use the following option2, given the fact that I know that the only reason that could prevent from turning p into an integer is the presence of that 'T'. 考虑到我知道可能阻止将p转换为整数的唯一原因是该“ T”的存在,我非常想使用以下option2。 Therefore, would it be unusual or less efficient to write this : 因此,编写此代码是不寻常的还是效率较低的:

#option2
def getListRank(self):
    for point in self.soup.findAll('td',class_="rank-cell"):
        p = (point.get_text().replace('\t','').replace('\n','')
                             .replace('\r','').replace(',',''))
        try:
            self.listRk.append(int(p))
        except:
            self.listRk.append(int(p.replace('T',''))                
    return self.listRk

I ask the questions because I read this before so I assume that it is "pythonic". 我问这些问题是因为我之前读过这篇文章,所以我认为它是“ pythonic”的。 However if there is a piece of explanation/convention I am more than interested. 但是,如果有一个解释/约定,我很感兴趣。

Thanks in advance 提前致谢

Don't use either. 都不使用。 Remove T along with the other characters, as @tobias_k suggested; 删除T以及其他字符,如@tobias_k建议; then you know that int(p) will succeed. 那么您知道 int(p)将成功。 You can do this more easily using re.sub as well, simplifying this enough to use a list comprehension instead of a for loop. 您也可以使用re.sub来更轻松地完成此操作,将其简化为足以使用列表推导而不是for循环。

import re

to_replace = re.compile(r'\t|\n|\r|T|,')
def getListRank(self):
    points = self.soup.findAll('td', class_="rank-cell")

    self.listRk = [int(re.sub(to_replace, "", p.get_text())) for p in points]
    return self.listRk

You can also use str.translate to remove your set of characters. 您也可以使用str.translate删除字符集。

self.listRk = [int(p.get_text().translate(None, "\r\n\tT,")) for p in points]

At least in CPython's interpreter, exceptions really don't cost much more, and are sometimes cheaper, particularly if the test would require more Python level code, while the exception would be raised implicitly by a C layer function. 至少在CPython的解释器中,异常确实不会花费更多,并且有时更便宜,尤其是在测试需要更多Python级代码的情况下,而异常将由C层函数隐式引发。

The reason to choose if checks over exceptions is usually a matter of style; 选择if检查异常的原因通常是样式问题。 save exceptions for actual exceptional cases, not as a generic control flow mechanism. 将例外情况保存为实际例外情况,而不是作为通用控制流程机制。 That said, Python is all about EAFP , so it tends to use exceptions for less exceptional purposes. 就是说,Python都是关于EAFP的 ,因此它倾向于出于例外目的使用异常。

Just please, for the love of god, don't use bare except blocks. 拜托,为了上帝的爱,除了砖块,不要裸露。 Catch the exception you expect, and no more, because otherwise you'll catch stuff that should never have been caught, eg if you typo append as apend , the AttributeError will be caught. 捕获您期望的异常,并且不再捕获该异常,因为否则,您将捕获本不应该捕获的内容,例如,如果append apend作为apend append ,则会捕获AttributeError

Of course, in your particular case, you could just skip the test completely. 当然,在您的特定情况下,您可以完全跳过测试。

self.listRk.append(int(p.replace('T',''))

works whether or not a T is in your string after all. 不管字符串中是否有T都可以工作。 Checking for it is pointless, just get rid of it if it's there and convert to int . 检查它是没有意义的,只要删除它就可以了,然后转换为int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM