英文:
Reworking loop in Python
问题
for i in [i for i in range(n) if status[i] == -1]:
<主要代码>
英文:
I have a Python loop that looks like this:
for i in range(n):
if (status[i]==-1):
<main code>
I'm sure there is a better way to do this - some kind of "where" in the iterator?
The code runs as expected, it is just inefficient and slow. If I have 200000 records and only 30 of them have a status[i]==-1, I don't want to examine all 200000.
答案1
得分: 4
在Python中,迭代列表的速度本质上较慢。尝试使用一些矢量化库,如_numpy_,它是用C实现的,可以执行类似这样的操作,速度可提高数百倍。例如:
import numpy as np
arr = np.array(status)
x = np.where(arr == -1)
print(x)
英文:
Iterating a Python list is inherently slow. Try some vectorization library as numpy, which is implemented in C and can perform operations like this several hundred times faster. E.g.
import numpy as np
arr = np.array(status)
x = np.where(arr == -1)
print(x)
答案2
得分: 2
对于状态中的每个元素:
如果 s 等于 -1:
英文:
for s in status:
if(s == -1):
This will look better for sure, and may be slightly more efficient.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论