![](/img/trans.png)
[英]Pythonic way of checking if a condition holds for any element of a list
[英]Pythonic way for checking equality in AND condition
我有一段代碼如下所示:
a = None
b = None
c = None
d = None
if a==None and b==None and c==None and d==None:
print("All are None")
else:
print("Someone is not None")
什么是 pythonic 方式或更短的方式來實現這一點,因為我有更多的變量要像這樣檢查?
您可以使用列表,並使用列表理解檢查列表中的所有項目:
l_list = [None, None, None, None, None]
if all(item is None for item in l_list):
print("All items are None")
您可以鏈接比較:
if a is b is c is d is None:
print("All are None")
else:
print("Someone is not None")
if not all((a, b, c, d)):
或者
if not any((a, b, c, d)):
如果你想檢查是否有任何項目不是None
這有幫助嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.