什么是简洁的python方式
if <none of the elements of this array are None>:
# do a bunch of stuff once
Run Code Online (Sandbox Code Playgroud)
该all内建对这个漂亮的.给定一个iterable,True如果iterable的所有元素都求值,则返回True.
if all(x is not None for x in array):
# your code
Run Code Online (Sandbox Code Playgroud)
当然在这种情况下,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)
然而,使用any和all经常(无论是在Python中还是在符号逻辑中)的人通常习惯使用De Morgan定律转换为"正常"形式.An any只是一个迭代的析取,而析取的否定是否定的结合,因此,这转化为Sam Mussmann的答案:
if all(element is not None for element in array):
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
118 次 |
| 最近记录: |