简体   繁体   中英

A concise way to say “none of the elements of an array are None”?

What's a concise python way to say

if <none of the elements of this array are None>:
   # do a bunch of stuff once

为什么不简单地

None not in lst

The all builtin is nice for this. Given an iterable, it returns True if all elements of the iterable evaluate to True .

if all(x is not None for x in array):
  # your code

Of course in this case, Jared's answer is obviously the shortest, and also the most readable. And it has other advantages (like automatically becoming O(1) or O(log N) if you switch from a list to a set or a SortedSet). But there will be cases where that doesn't work, and it's worth understanding how to get from your English-language statement, to the most direct translation, to the most idiomatic.

You start with "none of the elements in array are None".

Python doesn't have a "none of" function. But if you think about it, "none of" is exactly the same as "not any of". And it does have an "any of" function, any . So, the closest thing to a direct translation is:

if not any(element is None for element in array):

However, people who use any and all frequently (whether in Python, or in symbolic logic) usually get used to using De Morgan's law to translate to a "normal" form. An any is just an iterated disjunction, and the negation of a disjunction is the conjunction of the negations, so, this translates into Sam Mussmann's answer :

if all(element is not None for element in array):

你可以用全部

all(i is not None for i in l)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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