【问题标题】:Separating out zipped iterator into single iterator?将压缩迭代器分离成单个迭代器?
【发布时间】:2014-09-05 12:11:43
【问题描述】:

我的代码有两个二维 numpy 数组,zweights。 我正在像这样迭代它们(同时转置它们):

import statsmodels.api as sm
import numpy as np

for y1, w in zip(z.T, weights.T): # building the parameters per j class
    temp_g = sm.WLS(y1, iself.X, w).fit()

这很好,直到我开始使用 Numba 来加速我的代码。使用 Numba,我收到此错误:

numba.error.NumbaError: (see below)
--------------------- Numba Encountered Errors or Warnings ---------------------
        for y1, w in zip(z.T, weights.T): # building the parameters per j class
------------^
Error 82:12: Only a single target iteration variable is supported at the moment
--------------------------------------------------------------------------------

要解决这个问题,我想我可以这样做:

for y1 in z.T:
   for w in weights.T:
       temp_g = sm.WLS(y1, iself.X, w).fit()

但我还不太擅长 python,所以我只想知道这是否是最好的方法?或者是否有另一种更优化的方式?

【问题讨论】:

    标签: python for-loop numpy iterator numba


    【解决方案1】:

    Numba 似乎不支持赋值解包。分配给 one 目标,然后处理元组中的两个索引:

    for y1_w in zip(z.T, weights.T):
        temp_g = sm.WLS(y1_w[0], iself.X, y1_w[1]).fit()
    

    这里的y1_w 是一个包含z.Tweights.T 配对元素的元组,因此是两个元素的元组。您可以使用索引来处理每个元素。

    您可以可能在循环体中的for 语句之外使用赋值解包:

    for y1_w in zip(z.T, weights.T):
        y1, w = y1_w  # unpack the zip pair 'manually'
        temp_g = sm.WLS(y1, iself.X, w).fit()
    

    【讨论】:

      猜你喜欢
      • 2020-01-05
      • 1970-01-01
      • 2015-08-28
      • 1970-01-01
      • 2018-05-16
      • 2013-08-01
      • 1970-01-01
      • 2015-06-22
      相关资源
      最近更新 更多