通过执行依赖于多个索引的操作来创建列表-python

时间:2018-07-16 11:20:10

标签: python arrays loops numpy

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

Sub Macro2()
'
' Macro2 Macro
'

'
    Range("A1:D3").Select
    ActiveWorkbook.Worksheets("Sheet3").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet3").Sort.SortFields.Add2 Key:=Range("A1:D1") _
        , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortTextAsNumbers
    With ActiveWorkbook.Worksheets("Sheet3").Sort
        .SetRange Range("A1:D3")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlLeftToRight
        .SortMethod = xlPinYin
        .Apply
    End With
    Application.CutCopyMode = False
    ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$1:$D$3"), , xlYes).Name = _
        "Table2"
    Range("Table2[#All]").Select
End Sub

我发现此解决方案的速度略快(尽管我仍然认为可能会有更好的解决方案!):

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

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

2 个答案:

答案 0 :(得分:1)

您可以将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]

答案 1 :(得分: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

这是一个功能强大的工具,尽管不了解其牢固性。