【问题标题】:Create a list by doing operations which depend on multiple indices - python通过执行依赖于多个索引的操作来创建列表 - python
【发布时间】:2018-12-23 22:17:43
【问题描述】:

我正在寻找一种更快、更 pythonic 的方法来创建一个列表,该列表的元素依赖于另一个列表中的多个索引。代码示例:

import numpy as np
xrandomsorted = np.sort(np.random.randn(1000000)) #input which needs to be used
Npts = int(len(xrandomsorted)/3)

#Part to be optimised begins here
final_list = np.zeros(Npts)

for i in range(Npts): 
    xval = 12 - 3*xrandomsorted[i] + 7*xrandomsorted[2*i] - xrandomsorted[3*i]
    final_list[i] = xval

我发现这个解决方案稍微快一些(尽管我仍然认为可能有更好的解决方案!):

list1 = xrandomsorted[0:Npts]
list2 = xrandomsorted[::2][0:Npts]
list3 = xrandomsorted[::3][0:Npts]

final_list = []

for value1, value2, value3 in zip(list1, list2, list3):
    xval = 12 - 3*value1 + 7*value2 -value3
    final_list.append(xval)

有没有其他方法可以在不使用 numba/cython 的情况下使代码更快?

【问题讨论】:

    标签: python arrays loops numpy


    【解决方案1】:

    你试过itemgetter吗?:

    for i in range(Npts): 
        a,b,c = operator.itemgetter(i,2*i,3*1)(xrandomsorted)
        xval = 12 - 3*a + 7*b - c
        final_list[i] = xval
    

    它是一个强大的工具,虽然不知道牢度。

    【讨论】:

      【解决方案2】:

      您可以将 NumPy 切片用于矢量化解决方案:

      n = Npts
      A = xrandomsorted
      res = 12 - 3*A[:n] + 7*A[:n*2:2] - A[:n*3:3]
      

      语法类似于 Python list 切片语法,即arr[start : stop : step]

      【讨论】:

        猜你喜欢
        • 2014-08-19
        • 2019-01-10
        • 2018-11-12
        • 2013-10-05
        • 1970-01-01
        • 1970-01-01
        • 2022-10-15
        • 2021-03-05
        • 2016-02-15
        相关资源
        最近更新 更多