【问题标题】:Python maintaining list of valuesPython维护值列表
【发布时间】:2015-07-30 15:22:05
【问题描述】:

我正在尝试使用 3 个特定列表(峰值、X3 和 Y3)制作颜色图。我使用插入函数构建的列表代码。代码如下:

for k in range(112):

   if (act_info.nb_act[k]) >0:
       max_V.insert(k,np.max(array_data[:,k]))#find the maximum voltage for the set of samples of each channel
       min_V.insert(k,np.min(array_data[:,k]))                     #find the minimum voltage for the set of samples of each channe
       dif = ((((max_V[k] - min_V[k])/(4096.0))*10.0)/elec_array.chan[k].gain)*1000
       peak.insert(k,dif)  #then compute the difference between the max and min to find the peak-to-peak value
       X3.insert(k, elec_array.chan[k].x)                          #get the coordinates
       Y3.insert(k, elec_array.chan[k].y)

    else:

        Z2as[k] = k
        aa=aa+1

我的目的是在 act_info.b_act[k] 不大于零时获取所有 3 个列表并记录。 当我尝试运行此代码时,会出现此错误:

Traceback (most recent call last):
  File "/Users/AhmedNiri/Ahmed/2D_Mapping_Program_V8.py", line 433, in on_scar_button
    self.scar_map(file_info, elec_array, aux_elec, act_info, act, act_type, array_data)
  File "/Users/AhmedNiri/Ahmed/2D_Mapping_Program_V8.py", line 911, in scar_map
    dif = ((((max_V[k] - min_V[k])/(4096.0))*10.0)/elec_array.chan[k].gain)*1000
IndexError: list index out of range

似乎当 act_info.b_act[k] 小于 0 时,它进入 else 语句记录它小于零,然后似乎中断了列表生成,因此给了我这个错误。我使用 python 的时间太长了,不知道如何解决这个问题。

提前感谢您的帮助:)。

【问题讨论】:

    标签: python list python-2.7 linked-list


    【解决方案1】:

    您的堆栈跟踪准确地告诉您刚才所说的内容。索引 k 超出范围。它试图调用数据中不存在的东西(列表、字典或元组等)。为避免这使您的程序崩溃,请使用 try: except: 块包装您的 if 条件。

    for k in range(112):
    
      try:
    
         if (act_info.nb_act[k]) >0:
             max_V.insert(k,np.max(array_data[:,k]))#find the maximum voltage for the set of samples of each channel
             min_V.insert(k,np.min(array_data[:,k]))                     #find the minimum voltage for the set of samples of each channe
             dif = ((((max_V[k] - min_V[k])/(4096.0))*10.0)/elec_array.chan[k].gain)*1000
             peak.insert(k,dif)  #then compute the difference between the max and min to find the peak-to-peak value
             X3.insert(k, elec_array.chan[k].x)                          #get the coordinates
             Y3.insert(k, elec_array.chan[k].y)
    
        except IndexError:
          pass
    

    它被设置为通过,所以如果这种情况再次发生,它不会让你的程序崩溃。你可以设置它关闭程序,或者标记用户然后忽略它等等。

    【讨论】:

    • 但是序列被破坏后如何​​继续。因为如果我理解正确,这段代码会传递异常,但是异常之后的数字呢?因为它们似乎没有被使用,我想使用它们。能否请您详细说明,感谢您的帮助。 @awbemauler
    • 你说的是 else 语句中的代码吗?
    • 不,我在说 else 之后,似乎没有生成值。这意味着我猜该列表在异常处停止并且不会生成列表的其余部分。我想要列表的其余部分的原因是生成地图。 @awbemauler
    猜你喜欢
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 2023-01-30
    • 2018-09-22
    • 2021-12-17
    相关资源
    最近更新 更多