简体   繁体   English

哪种方式最好跳过'NoneType'变量?

[英]Which way is better to skip the 'NoneType' variable?

A list contains several NoneType elements. 列表包含几个NoneType元素。 To skip the NoneType , 要跳过NoneType

for item in list :
    if item is not None :
        fp.write(item + '\n')

#OR

for item in list : 
    try :
        fp.write(item + '\n')
    except :
        pass

Which one is better and why? 哪一个更好,为什么?

As a general rule of thumb, you should not really be using the try: except: pattern for control flow if you can help it. 作为一般的经验法则,你不应该真的使用try: except:模式来控制流程,如果你可以帮助它。 There is some overhead involved with raising an exception that is unnecessary in this context. 在此上下文中引发异常时需要一些开销。 Hope this helps. 希望这可以帮助。

As people mentioned in the comment the try approach is not the good way, because you might skip an element because of any other exceptions that rise in that block. 正如人们在评论中提到的那样, try方法不是好方法,因为你可能会因为该块中出现的任何其他异常而跳过一个元素。

So the first option is better. 所以第一个选择更好。 Here is an alternative, where you can be sure that all elements are not None , but it will consume more memory: 这是一个替代方案,您可以确保所有元素都不是None ,但它会占用更多内存:

for item in (element for element in list if element is not None):
    fp.write(item + '\n')

PS do not use built-in names as variable names, in your case - list . 在您的案例list ,PS不使用内置名称作为变量名称。

The second won't be good as it will throw an exception whenever a None type element is encountered. 第二个不好,因为每当遇到None类型元素时它都会抛出异常。 Exception will handled in it's own way in python . 异常将在python中以自己的方式处理。

In your case you are giving a pass , so that will be done . 在你的情况下,你正在通过,所以这将完成。

A more cleanest way would be : 更干净的方式是:

clean = [x for x in lis if x != None]

or As pointed in the comments you could also use is not, even if it essentially compiles to the same bytecode: 或者如您在注释中所指出的那样,即使它基本上编译为相同的字节码,也可以使用它:

clean = [x for x in lis if x is not None]

Hope this helps . 希望这可以帮助 。 When in rome do like Romans :) 在罗马时像罗马人一样:)

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

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