[英]Most time/space efficient way to check if all elements in list of integers are 0
This is an implementation question for Python 2.7 这是Python 2.7的实现问题
Say I have a list of integers called nums
, and I need to check if all values in nums
are equal to zero. 假设我有一个称为nums
的整数列表,我需要检查nums
中的所有值是否等于零。 nums
contains many elements (ie more than 10000), with many repeating values. nums
包含许多元素(即大于10000),并且具有许多重复值。
Using all()
: 使用all()
:
if all(n == 0 for n in set(nums)): # I assume this conversion from list to set helps?
# do something
Using set subtraction: 使用集合减法:
if set(nums) - {0} == set([]):
# do something
Edit: better way to do the above approach, courtesy of user U9-Forward 编辑:由用户U9-Forward提供的更好的方法来完成上述方法
if set(nums) == {0}:
# do something
How do the time and space complexities compare for each of these approaches? 每种方法的时间和空间复杂度如何比较? Is there a more efficient way to check this? 有没有更有效的方法来检查这一点?
Note: for this case, I am trying to avoid using numpy/pandas. 注意:在这种情况下,我试图避免使用numpy / pandas。
Any set conversion of nums
won't help as it will iterate the entire list: nums
任何组转换都将无济于事,因为它将迭代整个列表:
if all(n == 0 for n in nums):
# ...
is just fine as it stops at the first non-zero element, disregarding the remainder. 很好,因为它在第一个非零元素处停止,而忽略了其余部分。
Asymptotically, all these approaches are linear with random data. 渐近地,所有这些方法都是线性的,具有随机数据。 Implementational details (no repeated function calls on the generator) makes not any(nums)
even faster, but that relies on the absence of any other falsy elements but 0
, eg ''
or None
. 实现细节(在生成器上没有重复的函数调用) not any(nums)
使not any(nums)
更快,但这取决于除0
以外没有其他虚假元素,例如''
或None
。
not any(nums)
is probably the fastest because it will stop when/if it finds any non-zero element. not any(nums)
可能是最快的,因为它会在/发现任何非零元素时停止。
Performance comparison: 性能比较:
a = range(10000)
b = [0] * 10000
%timeit not any(a) # 72 ns, fastest for non-zero lists
%timeit not any(b) # 33 ns, fastest for zero lists
%timeit all(n == 0 for n in a) # 365 ns
%timeit all(n == 0 for n in b) # 350 µs
%timeit set(a)=={0} # 228 µs
%timeit set(b)=={0} # 58 µs
如果可以使用numpy,则(np.array(nums) == 0).all()
应该这样做。
Additionally to @schwobaseggl's answer, second example could be even better: 除了@schwobaseggl的答案之外,第二个示例甚至可能更好:
if set(nums)=={0}:
# do something
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.