简体   繁体   English

如果列表为空,Python 返回 False

[英]Python return False if list is empty

In one coding example i saw the following code snippet that returns True if the list is empty and False if not在一个编码示例中,我看到以下代码片段,如果列表为空则返回True,否则返回False

return a == []

the reason for that is to avoid writing这样做的原因是为了避免写作

if a:
    return False
else:
    return True

In a real example with multiple thousands of entries, is there any speed difference i should be aware of?在具有数千个条目的真实示例中,我应该注意任何速度差异吗?

No. There is no speed difference in either case.不会。两种情况下都没有速度差异。 Since in both cases the length of the list is checked first.因为在这两种情况下,首先检查列表的length In the first case, the len of a is compared with the len of [] before any further comparison.在第一种情况下,该lena与比较len[]前的任何进一步的比较。 Most times the len should differ, so the test just returns immediately.大多数时候len应该不同,所以测试会立即返回。

But the more pythonic way would be to just return not a or convert it using bool and then return it:但是更pythonic的方法是return not a或使用bool转换它然后返回它:

return not a

# or 

return not bool(a)

If you're asking which method would faster if put in a function(hence the return 's), then I used the timeit module to do a little testing.如果你问哪个方法放在函数中会更快(因此是return ),那么我使用timeit模块进行了一些测试。 I put each method in a function, and then ran the program to see which function ran faster.我把每个方法放在一个函数中,然后运行程序看看哪个函数跑得更快。 Here is the program:这是程序:

import timeit

def is_empty2():
    a = []
    if a:
        return True
    else:
        return False

def is_empty1():
    a = []
    return a == []


print("Time for method 2:")
print(timeit.timeit(is_empty2))
print("")
print("Time for method 1:")
print(timeit.timeit(is_empty1))

I ran the program five times, each time recording the speed for each function.我运行了五次程序,每次都记录每个函数的速度。 After getting an average for each time, here is what I came up with:在获得每次的平均值后,这是我想出的:

method one speed(milliseconds): 0.2571859563796641
-----------------------------   ------------------
method two speed(milliseconds): 0.2679253742685615

At least from my testing above, the first method you described in your question was slightly faster than the second method.至少从我上面的测试来看,您在问题中描述的第一种方法比第二种方法快。 Of course those numbers above could drastically change depending on what exactly is inside those two functions.当然,根据这两个函数内部的确切内容,上面的数字可能会发生巨大变化。

I agree however, with what Cdarke said in the comments.但是,我同意 Cdarke 在评论中所说的话。 Go with the one that is the most clear and concise.选择最清晰简洁的那个。 Don't go with one option solely based upon its speed.不要仅仅根据其速度选择一个选项。 in the words of Guido van Rosom: Readability counts .用 Guido van Rosom 的话来说:可读性很重要

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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