相关疑难解决方法(0)

Python`如果x不是None`或`if not x is None`?

我一直认为if not x is None版本更清晰,但谷歌的风格指南PEP-8都使用if x is not None.是否存在任何轻微的性能差异(我假设没有),是否存在任何一个真正不合适的情况(使另一个成为我公约的明显赢家)?*

*我指的是任何单身人士,而不仅仅是None.

...比较像无的单身人士.使用是否.

python coding-style boolean-expression

687
推荐指数
7
解决办法
69万
查看次数

检查多个变量是否为None的最pythonic方法是什么?

如果我有这样的结构:

def foo():
    a=None
    b=None
    c=None

    #...loop over a config file or command line options...

    if a is not None and b is not None and c is not None:
        doSomething(a,b,c)
    else:
        print "A config parameter is missing..."
Run Code Online (Sandbox Code Playgroud)

python中首选的语法是检查所有变量是否都设置为有用的值?是我写的还是其他更好的方式?

这与这个问题不同: 不是Python中的无测试 ......我正在寻找检查许多条件是否为None的首选方法.我输入的选项似乎很长而且非pythonic.

python

41
推荐指数
4
解决办法
2万
查看次数

空列表是否等于无?

可能重复:
当"if not []"成功时,为什么"[] == False"评估为False?

我是Python的三元运算符的新手

>>> 'true' if True else 'false'  true
   true
Run Code Online (Sandbox Code Playgroud)

我希望下面的代码输出为[],因为[]不等于None

>>> a=[]
>>> a==None
False
>>> a if a else None
None
Run Code Online (Sandbox Code Playgroud)

如果我错了,请求正确

谢谢赫马

python ironpython python-2.7 python-3.x

9
推荐指数
1
解决办法
3万
查看次数

检查xml ElementTree节点是否为None/False

myvar通过简单地检查变量是否具有非 - 无值值是否安全:

if myvar:
    print('Not None detected')
Run Code Online (Sandbox Code Playgroud)

我问这个是因为我有一个变量并且正在检查变量是否不是None简单if variable:但是检查失败了.该变量包含一些数据,但在if检查中评估为False .

完整代码:

from xml.etree import ElementTree as ElementTree

root = ElementTree.fromstring('Some xml string')

parameters = root.find('Some Tag')

udh = parameters.find('UDH')

if udh and udh.text:  # In this line the check is failing, though the udh variable has value: <Element 'UDH' at 0x7ff614337208>
    udh = udh.text
    # Other code
else:
    print('No UDH!')  # Getting this output
Run Code Online (Sandbox Code Playgroud)

python

7
推荐指数
1
解决办法
1万
查看次数

Python错误ByPassing

对于多个帖子很抱歉,我确实环顾四周,除了try方法之外找不到任何东西,这在某些情况下似乎很有用,而不是我的.

我正在寻找的是一种跳过错误的方法,所以只是没有在控制台中显示而不是停止脚本,只是一种绕过它们的方法.

即;

1. call a list
2. If list does not exist
3.     create the list
Run Code Online (Sandbox Code Playgroud)

python error-handling

2
推荐指数
1
解决办法
229
查看次数

“对象不是无”是否与对象相同?

我通常使用“不是无”来测试对象是否为空。我看到代码只使用'if object'。它们是一样的吗?

例如,

if Dog:
  ...
Run Code Online (Sandbox Code Playgroud)

VS

if Dog is not None:
  ...
Run Code Online (Sandbox Code Playgroud)

python

2
推荐指数
1
解决办法
538
查看次数

根据键值过滤python中的嵌套字典

如何根据键值过滤python中的嵌套字典:

d = {'data': {'country': 'US', 'city': 'New York', 'state': None},
     'tags': ['US', 'New York'],
     'type': 'country_info',
     'growth_rate': None
     }
Run Code Online (Sandbox Code Playgroud)

我想过滤这个字典以消除NoneType值,因此产生的字典应该是:

d = {'data': {'country': 'US', 'city': 'New York'},
     'tags': ['US', 'New York'],
     'type': 'country_info',
     }
Run Code Online (Sandbox Code Playgroud)

此外,dict可以有多个嵌套级别.我想从dict中删除所有NoneType值.

python dictionary

1
推荐指数
1
解决办法
2668
查看次数

Python:用十六进制分隔符分割字节

我正在处理几个二进制文件,并且想要解析存在的 UTF-8 字符串。

我目前有一个函数,它获取文件的起始位置,然后返回找到的字符串:

def str_extract(file, start, size, delimiter = None, index = None):
   file.seek(start)
   if (delimiter != None and index != None):
       return file.read(size).explode('0x00000000')[index] #incorrect
   else:
       return file.read(size)
Run Code Online (Sandbox Code Playgroud)

文件中的一些字符串是用 分隔的0x00 00 00 00,是否可以像PHP的explode那样分割这些字符串?我是 Python 新手,因此欢迎任何有关代码改进的建议。

样本文件:

48 00 65 00 6C 00 6C 00 6F 00 20 00 57 00 6F 00 72 00 6C 00 64 00 | 00 00 00 00 | 31 00 32 00 33 00也就是说Hello World123,我通过用条将00 00 00 …

python hex split

1
推荐指数
1
解决办法
1万
查看次数

调用类的构造函数作为其他类构造函数中的默认参数

问题

我试图在另一个类的构造函数的参数的默认赋值中调用一个类的构造函数,但是我遇到了构造函数未正确调用的问题。这里发生了什么?

代码说明

Bad类是不工作的情况和Good类是一个丑陋的解决办法来解决这个问题。Base.i每次Base.__init__调用构造函数时,该值都会增加,并且可以看出,它没有为o2对象正确增加,但似乎为每个o1,o3和正确增加o4

代码

class Base:
    i = 0
    def __init__(self):
        Base.i += 1
        self.i = Base.i

class Bad:
    def __init__(self, base = Base()):
        self.base = base

class Good:
    def __init__(self, base = None):
        if base is None:
            self.base = Base()
        else:
            self.base = base

if __name__ == "__main__":
    o1 = Bad()
    o2 = Bad()

    print("Bad:")
    print(f"o1.i: {o1.base.i}")
    print(f"o2.i: {o2.base.i}")

    o3 = Good() …
Run Code Online (Sandbox Code Playgroud)

python constructor initialization default-constructor default-arguments

0
推荐指数
1
解决办法
37
查看次数