如果 len(list) 在 Python 中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15905282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
if len(list) in Python
提问by mjswartz
I'm translating a Python code to C in order to take advantage of the parallelism available on HPC systems (its a painful process) and I've come across a conditional in Python the original programmer used that confuses me
我正在将 Python 代码转换为 C 以利用 HPC 系统上可用的并行性(这是一个痛苦的过程),并且我在 Python 中遇到了原始程序员使用的条件,这让我感到困惑
if rnum <> current_res:
alim = 0
if len(f): alim = f[-1]
What does if len(f) satisfy? I cannot find this convention used in this way anywhere online. I imagine it is a bad programming practice.
如果 len(f) 满足什么?我在网上的任何地方都找不到以这种方式使用的这种约定。我想这是一种糟糕的编程习惯。
Any help would be much appreciated!
任何帮助将非常感激!
采纳答案by Martijn Pieters
In Python, values that are considered 'empty', such as numeric 0, are considered False in a boolean context, and otherwise are True.
在 Python 中,被视为“空”的值,例如数字 0,在布尔上下文中被视为 False,否则为 True。
Thus, len(f)is True if fhas length, otherwise it is empty. If fis a standard Python sequence type then the code can be simplified to:
因此,len(f)如果f有长度则为真,否则为空。如果f是标准的 Python 序列类型,那么代码可以简化为:
if f: alim = f[-1]
because the same applies to sequences; empty is False, having a non-zero length means it's True.
因为这同样适用于序列;empty 是 False,具有非零长度意味着它是 True。
See Truth Value Testingin the Python documentation for all the important details.
有关所有重要细节,请参阅Python 文档中的真值测试。
Note that <>has been deprecated; you should really use !=instead.
请注意,<>已弃用;你真的应该!=改用。
回答by mgilson
In most cases if len(f):will be the same thing as if f:...
在大多数情况下,if len(f):将与if f:...相同
the reason is because if fhas no length, it will return 0which is a falsy value. Actually, truth testing actually checks the length of an object (__len__) under some circumstances.
原因是因为如果f没有长度,它会返回0一个假值。实际上,在某些情况下,真值测试实际上会检查对象 ( __len__)的长度。
回答by askewchan
This
这个
if len(f)
would translate to:
会翻译成:
if len(f) != 0
or in this case, since len(f)is never negative,
或者在这种情况下,因为len(f)永远不会是负数,
if len(f) > 0

