【问题标题】:Fastest way to iterate through loops in various scenarios在各种场景中迭代循环的最快方法
【发布时间】:2017-07-13 17:58:59
【问题描述】:

在对我们的源代码库进行广泛分析后,我们发现所有性能问题都是在循环一些巨大的列表时引起的。

导致问题的代码段落可以识别如下:

#ISSUE 1
myList = [i for j, i in enumerate(myList) if j not in anotherList]

#ISSUE 2
TargetIndex = next((myList.index(n) for n in myList if n > someBoundary), len(myList))

#ISSUE 3
def myFunction():
    for i in myList:
        if abs(i) > someLimit:
            return 0
    return 1

#ISSUE 4
for n,i in enumerate(myList):
    if abs(i) < someLimit:
        myList[n] = 0

我很确定一些numpy 专家可以写下四个单行代码,这将极大地提升我们的应用程序的性能。但是对于这些循环操作,也许还有比我不知道的numpy 更好的方法。

非常感谢有关该主题的任何建议。

【问题讨论】:

  • 这些都在列表上工作。为什么是 numpy 的问题?如果它们是数组,我们可能会建议更快的编译操作。但为此,我们需要了解 shape 和 dtype。
  • 嗨。所有列表元素的数据类型始终是浮点数,列表是平面的(没有列表的列表)。
  • 更多 numpy 上下文请查看stackoverflow.com/q/42356625

标签: python arrays performance python-2.7 numpy


【解决方案1】:

第一个问题:在 set 而不是 list 中进行查找

anotherSet = set(anotherList)
myList = [i for j, i in enumerate(myList) if j not in anotherSet]

第二个问题:当您已经在列表上进行迭代时,为什么还要计算 nindex?使用enumerate

TargetIndex = next((i for i,n in enumerate(myList) if n > someBoundary), len(myList))

对于问题 3 和 4,您无能为力,只能预先计算绝对值列表,这样您就不会在同一个列表上执行两次。

abs_vals = [abs(n) for n in myList]

例如,第 4 个 sn-p 变为:

for index,av in enumerate(abs_vals):
    if av < someLimit:
        myList[index] = 0

【讨论】:

  • 哇。那很快。非常感谢。我会试试看。
  • 效果很好。谢谢!
【解决方案2】:

作为警告,如果您想将数据保留为 numpy 数组,则必须进行更多更改,但这是您解决问题的方法。

import numpy as np

myArr=np.array(myList)

#1
myArr = myArr[np.in1d(np.arange(myArr.size), anotherList, invert = True)]

#2
TargetIndex = next(np.nonzero(myArr > someBoundary)[0].flat, myArr.size)

#3
def myFunction():
    return (np.abs(myArr) <= someLimit).astype(int)

#4
np.where(np.abs(myArr) < someLimit, 0, myArr)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 2019-04-08
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多