【问题标题】:Why do I get 'list index out of range' although the times-list values are there?尽管有时间列表值,为什么我会得到“列表索引超出范围”?
【发布时间】:2017-12-26 09:52:20
【问题描述】:

简介

首先,非常感谢您花时间查看我的问题和代码。我知道我的编码需要改进,但与所有新事物一样,是时候完善了。

背景

我正在使用不同的功能来执行以下操作:

  1. 导入多个文件(目前为 3 个)。每个文件都包含时间、压力和无效列。
  2. 将列表存储在字典中。例如。一本压力字典中的所有压力。
  3. 过滤压力数据并确保我仍有相应数量的时间数据点(对于每个文件)。

我在主函数中调用这些函数。

问题

在我第二次运行 DataFilter 函数中的时间循环之前,一切都运行良好。但是,我确实检查了我可以访问字典中所有三个不同的压力和时间列表。当函数第二次运行时,为什么此时我得到“索引超出范围”:t=timeFROMtimes [i]This is the output I get for the code

代码

#IMPORT LIBRARIES
import glob
import pandas as pd
import matplotlib.pyplot as plt, numpy as np
from scipy.interpolate import spline

#INPUT PARAMETERS
max_iter = 3 #maximum number of iterations
i = 0 #starting number of iteration
tcounter = 0
number_of_files = 3 #number of files in directory
sourcePath = 'C:\\Users\\*' #not displaying actual directory
list_of_source_files = glob.glob(sourcePath + '/*.TXT')
pressures = {} #initialize a dictionary
times ={} #initialize a dictionary

#GET SPECIFIC FILE & PRESSURE, TIME VALUES 
def Get_source_files(list_of_source_files,i):
    #print('Get_source_files')
    with open(list_of_source_files[i]) as source_file:
        print("file entered:",i+1)
        lst = [] 
        for line in source_file:
            lst.append([ float(x) for x in line.split()])
        time = np.array([ x[0] for x in lst]) #first row in file and make array
        void = np.array([ x[1] for x in lst]) #second row in file and make array
        pressure =(np.array([ x[2] for x in lst]))*-1 #etc. & change the sign of the imported pressure data
    return pressure,time

#SAVE THE TIME AND PRESSURE IN DICTIONARIES
def SaveInDictionary (Pressure,time,i):
    #print('SaveInDictionary')
    pressures[i]=[Pressure]
    times[i]=[time]
    return pressures,times

#FILTER PRESSURE DATA AND ADJUST TIME
def FilterData (pressureFROMpressures,timeFROMtimes,i):
    print('FilterData')
    t=timeFROMtimes [i]
    p=pressureFROMpressures[i]
    data_points=int((t[0]-t[-1])/-0.02) #determine nr of data points per column of the imported file
    filtered_pressure = [] #create an empty list for the filtered pressure
    pcounter = 0 #initiate a counter
    tcounter = 0
    time_new =[0,0.02] #these initial values are needed for the for-loop

    for j in range(data_points): 
        if p[j]<8: #filter out all garbage pressure data points above 8 bar
            if p[j]>0:
                filtered_pressure.append(p[j]) #append the empty list ofsave all the new pressure values in new_pressure
                pcounter += 1

    for i in range(pcounter-1):
        time_new[0]=0
        time_new[i+1]=time_new[i]+0.02 #add 0.02 to the previous value
        time_new.append(time) #append the time list
        tcounter += 1 #increment the counter
    del time_new[-1] #somehow a list of the entire time is formed at the end that should be removed
    return filtered_pressure, time_new

#MAIN!!
P = list()
while (i <= number_of_files and i!=max_iter):
    pressure,time = Get_source_files(list_of_source_files,i) #return pressure and time from specific file
    pressures, times = SaveInDictionary (pressure,time,i)#save pressure and time in the dictionaries
    i+=1 #increment i to loop
print('P1=',pressures[0])
print('P2=',pressures[1])
print('P3=',pressures[2])
print('t1=',times[0])
print('t2=',times[1])
print('t3=',times[2])

#I took this out of the main function to check my error:
for i in range(2):
    filtered_pressure,changed_time = FilterData(pressures[i],times[i],i)
    finalP, finalT = SaveInDictionary (filtered_pressure,changed_time,i)#save pressure and time in the dictionaries

【问题讨论】:

  • 请修正缩进。我试图复制/粘贴您的代码,但由于缩进错误,它无法工作。另外,请提供您遇到的错误的回溯。
  • @CoryMadden,我已经修复了缩进并添加了我得到的输出图像。感谢您的宝贵时间。

标签: python function dictionary iteration indexoutofboundsexception


【解决方案1】:

在循环中,您从已经索引到times 的主函数中取出,但在

#I took this out of the main function to check my error:
for i in range(2):
    filtered_pressure,changed_time = FilterData(pressures[i],times[i],i)
    # Here you call FilterData with times[i]

但在 FilterData 函数中,您调用传递的变量 timeFROMtimes 您再次使用 i 对其进行索引:

def FilterData (pressureFROMpressures,timeFROMtimes,i):
    print('FilterData')
    t=timeFROMtimes [i]  # <-- right here 

这看起来很奇怪。尝试删除其中一个索引运算符 ([i]),同时为 pressures 删除。

编辑

正如@strubbly 指出的那样,在您的SaveInDictionary 函数中,您分配值[Pressure]。方括号表示一个包含一个元素的列表,numpy 数组Pressure。这可以在您的错误消息中看到,当您打印 P1-3 和 t1-3 时,通过数组前的左括号。 要直接保存您的 numpy 数组,请松开括号:

def save_in_dictionary(pressure_array, time, i):
    pressures[i] = pressure_array
    times[i] = time
    return pressures, times

【讨论】:

  • 是的 - 它需要比这更多的改变 - 因为 OP 将字典中的条目构建为 1 元素列表。这也需要改变。
  • @m00am,谢谢你的回答。我已经为timespressures 删除了索引运算符([i]),但是这样做我得到了这个错误:TypeError: only length-1 arrays can be converted to Python scalars
  • @strubbly,请您详细说明一下您的字典是 1 元素列表是什么意思?
  • @strubbly 确实。感谢您指出了这一点。当我冲出去吃午饭时,我过分了;)
  • @m00am,抱歉我反应太快了。您看到我删除了我的评论,因为我设法修复了它。我的代码现在完美运行。感谢您的帮助:)
猜你喜欢
  • 1970-01-01
  • 2023-02-22
  • 1970-01-01
  • 2020-09-04
  • 2020-08-18
  • 1970-01-01
  • 2011-11-30
  • 2020-10-11
  • 1970-01-01
相关资源
最近更新 更多