一种简洁的方式来说"阵列中没有一个元素是无"的?

Gre*_*ade 1 python python-2.7

什么是简洁的python方式

if <none of the elements of this array are None>:
   # do a bunch of stuff once
Run Code Online (Sandbox Code Playgroud)

Jar*_*red 11

为什么不简单,

None not in lst
Run Code Online (Sandbox Code Playgroud)


Sam*_*ann 7

all内建对这个漂亮的.给定一个iterable,True如果iterable的所有元素都求值,则返回True.

if all(x is not None for x in array):
  # your code
Run Code Online (Sandbox Code Playgroud)

  • @GreenAsJade:实际上,现在我想起来了,Sam Mussmann已经隐瞒了它......并且很多人会这样做而不考虑它(至少我会这样做,Sam做了......),所以绝对值得学习这两个是等价的. (2认同)

aba*_*ert 5

当然在这种情况下,Jared的答案显然是最短的,也是最具可读性的.它还有其他优点(例如,如果从列表切换到set或SortedSet,则会自动变为O(1)或O(log N)).但是有些情况下这种情况不起作用,并且值得理解如何从英语语句,最直接的翻译,到最惯用的翻译.

首先,"数组中没有元素是None".

Python没有"无"功能.但是如果你想一想,"没有"与"不是任何一个"完全相同.它确实具有"任何"功能,any.因此,与直接翻译最接近的是:

if not any(element is None for element in array):
Run Code Online (Sandbox Code Playgroud)

然而,使用anyall经常(无论是在Python中还是在符号逻辑中)的人通常习惯使用De Morgan定律转换为"正常"形式.An any只是一个迭代的析取,而取的否定是否定的结合,因此,这转化为Sam Mussmann的答案:

if all(element is not None for element in array):
Run Code Online (Sandbox Code Playgroud)