[英]What is the best way to reset (re-initialize) a list of integers (to 0) in Python
Given a list of integers ( list_nb
) of fixed size ( n
), what is the best way to reset (re-initialize) all the values to 0.给定一个固定大小 (
n
) 的整数列表 ( list_nb
),将所有值重置(重新初始化)为 0 的最佳方法是什么。
I already tried two methods, 1) using a loop to reset all elements one by one, 2) a new list with the same size (where all elements are at 0).我已经尝试了两种方法,1)使用循环来一个一个地重置所有元素,2)一个具有相同大小的新列表(所有元素都为 0)。
The second method clearly gives better results in terms of execution time.第二种方法显然在执行时间方面给出了更好的结果。
import time
n = 200_000_000
list_nb = [0]*n
# some lines of code that change the list_nb ....
# method 1 to reset
start_time = time.time()
for i in range(len(list_nb)):
list_nb[i] = 0
end_time = time.time()
print("Method 1 time = ",end_time-start_time," s")
# method 2 to reset
start_time = time.time()
list_nb = [0]*n
end_time = time.time()
print("Method 2 time = ",end_time-start_time," s")
Result:结果:
I don't know if there is any other way to do it.我不知道是否还有其他方法可以做到这一点。
Thanks.谢谢。
Method 2 is clearly superior on speed, and it's easy to understand for anyone familiar with Python sequence multiplication.方法2在速度上显然更胜一筹,对于熟悉Python序列乘法的人来说很容易理解。 A warning: It's not resetting the contents of the
list
;警告:它不会重置
list
的内容; it's making a whole new list
and rebinding the name to that new list
.它正在制作一个全新的
list
并将名称重新绑定到该新list
。 So if list_nb
was an argument to a function, the caller's copy of the list
would not be changed.因此,如果
list_nb
是 function 的参数,则不会更改调用者的list
副本。 If that's what you want, great, but if you want the contents to be changed in place, change it to:如果这就是您想要的,很好,但是如果您想更改内容,请将其更改为:
list_nb[:] = [0]*n # Or itertools.repeat(0, n), though CPython doesn't speed it up
which uses slice assignment to replace the contents of the existing list
in-place.它使用切片分配来替换现有
list
的内容。 It takes about twice as long (it builds a new list
, copies from it, then throws it away) as list_nb = [0]*n
, but if you need in-place mutation, it's worth it.它花费的时间大约是
list_nb = [0]*n
的两倍(它构建一个新list
,从中复制,然后将其丢弃),但是如果您需要就地突变,这是值得的。
I think the best way to do it is overwriting the list as you did in method #2.我认为最好的方法是像在方法 #2 中那样覆盖列表。 It's easier to overwrite the existing list than replacing every element in the list with 0. I believe there is no faster way to do it, but I might be wrong.
覆盖现有列表比用 0 替换列表中的每个元素更容易。我相信没有更快的方法可以做到这一点,但我可能错了。 Nice job !
不错的工作 !
Using numpy is pretty quick.使用 numpy 非常快。
import numpy as np
import time
n= 200000000
start_time = time.time()
list_nb = np.zeros(n)
end_time = time.time()
print(end_time-start_time)
This takes me 0.003000497817993164
这需要我
0.003000497817993164
If you are ready to use numpy:如果您准备好使用 numpy:
start_time = time.time()
a = numpy.zeros(n, dtype=object)
end_time = time.time()
print("Method 0 time = ",end_time-start_time," s")
gives给
('Method 0 time = ', 0.8265918731689453, ' s')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.