在Python中重新设计循环

huangapple go评论52阅读模式
英文:

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):
      &lt;main code&gt;

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.

huangapple
  • 本文由 发表于 2023年3月7日 23:00:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75663642.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定