簡體   English   中英

檢查多個變量是否不是None的最pythonic方法是什么?

[英]What is the most pythonic way to check if multiple variables are not None?

如果我有這樣的構造:

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..."

python 中檢查所有變量是否都設置為有用值的首選語法是什么? 是像我寫的那樣,還是其他更好的方法?

這與這個問題不同: not None test in Python ...我正在尋找檢查許多條件是否不是 None 的首選方法。 我輸入的選項似乎很長且非pythonic。

它可以做得更簡單,真的

if None not in (a, b, c, d):
    pass

更新:

正如 slashCoder 正確評論的那樣,上面的代碼隱含地做了 a == None、b == None 等。這種做法是不受歡迎的。 相等運算符可以重載,而不是 None 可以變為等於 None。 你可能會說它永遠不會發生。 好吧,它不會,直到它發生。 所以,為了安全起見,如果你想檢查沒有一個對象是 None 你可以使用這種方法

if not [x for x in (a, b, c, d) if x is None]:
    pass

它有點慢且表現力較差,但它仍然相當快和短。

你這樣做的方式沒有任何問題。

如果你有很多變量,你可以把它們放在一個列表中並使用all

if all(v is not None for v in [A, B, C, D, E]):

我知道這是一個老問題,但我想添加一個我認為更好的答案。

如果必須檢查的所有元素都是可散列的,則可以使用集合而不是列表或元組。

>>> None not in {1, 84, 'String', (6, 'Tuple'), 3}

這比其他答案中的方法快得多。

$ python3 -m timeit "all(v is not None for v in [1, 84, 'String', (6, 'Tuple'), 3])"
200000 loops, best of 5: 999 nsec per loop

$ python3 -m timeit "None not in [1, 84, 'String', (6, 'Tuple'), 3]"
2000000 loops, best of 5: 184 nsec per loop

$ python3 -m timeit "None not in (1, 84, 'String', (6, 'Tuple'), 3)"
2000000 loops, best of 5: 184 nsec per loop

python3 -m timeit "None not in {1, 84, 'String', (6, 'Tuple'), 3}"
5000000 loops, best of 5: 48.6 nsec per loop

此方法的另一個優點是,即使有人將類的__eq__方法定義為始終返回True ,它也會為您提供正確的答案。 (當然,如果他們定義__hash__方法return hash(None) ,這個方法將不起作用。但沒有人應該這樣做,因為它會__hash__定義散列的目的。)

class my_int(int):
    def __init__(self, parent):
        super().__init__()

    def __eq__(self, other):
        return True

    def __hash__(self):
        return hash(super())

print(all(v is not None for v in [1, my_int(6), 2])) # True (correct)
print(None not in [1, my_int(6), 2])                 # False (wrong)
print(None not in (1, my_int(6), 2))                 # False (wrong)
print(None not in {1, my_int(6), 2})                 # True (correct)

對於 OP 提出的特定案例

if not all([a, b, c])

就足夠了。

all([a, b, c])

如果缺少任何參數,則計算結果為 False。

寫一個單獨的答案,因為我不知道在作為評論添加時如何格式化代碼。

Eternal_N00B 的解決方案與 Daniel Roseman 的解決方案不同。 考慮例如:

>>> all(v is not None for v in [False])
True
>>> all([False])
False
x = 'a'
y = 'b'
z = 'c'

if all(item is not None for item in [x, y, x]):
    print('Multiple variables are NOT None')
else:
    print('At least one of the variables stores a None value')

我認為,補充丹尼爾羅斯曼的答案:

if all([a,b,c,d]):

更清潔

由於all()內置函數已遍歷列表檢查None

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM