索引超出范围,仅在函数python内部

时间:2018-06-27 15:19:35

标签: python-2.7 loops indexing append indexoutofrangeexception

我真的不明白这里发生了什么。我有一个功能:

def get_appliance_status(appliance):
    appliance_data = None
    status_color = SENSOR_STATUS_COLOR_UNKNOWN
    status_message = 'No Appliance Data Available'

    try:
        appliance_data = ApplianceData.objects.filter(appliance=appliance).latest('timestamp')

    except Exception as ex:
        print ex
    else:
        if appliance_data:
            status_color = SENSOR_STATUS_COLOR_OK
            status_message = 'Appliance Temperature and Pressure values are within designed ranges.'
            temperature_status = ''
            pressure_status = ''


            # status of inside box temp and food temps 1-4
            if appliance_data.temperature_4_f > appliance.max_temperature or \
               appliance_data.temperature_5_f > appliance.max_temperature or \
               appliance_data.temperature_6_f > appliance.max_temperature or \
               appliance_data.temperature_7_f > appliance.max_temperature or \
               appliance_data.temperature_8_f > appliance.max_temperature:
                status_color = SENSOR_STATUS_COLOR_WARN
                temperature_status = 'Appliance Temperature is outside designed ranges. '
                status_message = temperature_status

            if est_obj > timestamp + timedelta(minutes=15) or \
               est_obj > timestamp + timedelta(minutes=15) and \
               appliance_data.temperature_4_f > appliance.max_temperature:
                status_color = SENSOR_STATUS_COLOR_CRITICAL
                status_message = "Polar Board Has Lost Connection/Power Failure, Critical"
                #textclient.text(textclient.Brian, "Polar Board has lost connection" + " " + appliance.name)

            if appliance_data.power_1_amps > 0  and \
               appliance_data.power_2_amps == 0:
                status_color = SENSOR_STATUS_COLOR_EMERGENCY
                status_message = "Condenser Motor Fail-Emergency"

            if appliance_data.power_1_amps == 0 and \
               appliance_data.power_2_amps > 0:
                status_color = SENSOR_STATUS_COLOR_EMERGENCY
                status_message = "Compressor Motor Fail-Emergency"  

            if appliance_data.power_1_amps == 0 and \
               appliance_data.power_2_amps == 0 and \
               appliance_data.power_3_amps == 0 and \
               appliance_data.power_4_amps == 0:
                status_color = SENSOR_STATUS_COLOR_EMERGENCY
                status_message = "Power failure- Emergency"

            if appliance_data.pressure_1_psi < 8 and \
               appliance_data.pressure_2_psi < 7 and \
               appliance_data.power_1_amps == 0 and \
               appliance_data.power_2_amps == 0 and \
               appliance_data.power_3_amps > 0 and \
               appliance_data.power_4_amps > 0:
                status_color = SENSOR_STATUS_COLOR_EMERGENCY
                status_message = "No Pressure, Condenser/Compressor failure, Emergency"

            if appliance_data.pressure_1_psi > appliance.max_pressure_1 or \
               appliance_data.pressure_1_psi < appliance.min_pressure_1 or \
               appliance_data.pressure_2_psi > appliance.max_pressure_2 or \
               appliance_data.pressure_2_psi < appliance.min_pressure_2:
                status_color = SENSOR_STATUS_COLOR_WARN
                status_message = ''
                pressure_status = 'Appliance Pressure is outside designed ranges.'
                status_message = ' '.join((temperature_status, pressure_status))

            if appliance_data.power_3_amps == 0 and \
               appliance_data.power_4_amps > 0:
                status_color = SENSOR_STATUS_COLOR_CRITICAL
                status_message = "Evaporator Fan 1 Failure, Critical"

            if appliance_data.power_3_amps > 0 and \
               appliance_data.power_4_amps == 0:
                status_color = SENSOR_STATUS_COLOR_CRITICAL
                status_message = "Evaporator Fan 2 Failure, Critical "


            for item in my_appliance:
                if item.temperature_4_f > appliance.max_temperature:
                    above_temp.append(item.timestamp.astimezone(local_tz).strftime('%H:%M'))
                else:
                    break
            print(above_temp)

    return '<span class="status" style="background-color:' + status_color +';" title="' + status_message + '"></span>'

问题出在这里:

        above_temp=[]
        for item in my_appliance:
            if item.temperature_4_f > appliance.max_temperature:
               above_temp.append(item.timestamp.astimezone(local_tz)
              .strftime('%H:%M'))
            else:
                break
        print(above_temp)

如果我尝试打印above_temp[0],则会收到超出范围的错误。我可以使用above_temp[0:1]访问第一个元素。但是,这将返回此元素的列表,这不是我想要的。当我print(above_temp)时,我得到一个[],然后得到所需的列表。我真的想要这个列表的第一个和最后一个元素。根据列表的len,索引更改的最后一个元素。如果我在函数外运行相同的代码,则它将按预期工作。我需要它在此函数中运行。为什么它最初返回一个空列表,为什么我不能只使用索引来访问此函数中的元素? 这是我运行此程序后得到的:

[]
['11:17', '11:14', '11:12', '11:10', '11:08', '11:06', '11:04', '11:02',
 '11:00', '10:58', '10:56', '10:53', '10:51', '10:49', '10:47', '10:45', 
 '10:43', '10:41', '10:39', '10:37', '10:35', '10:32', '10:30', '10:28', 
 '10:26', '10:24', '10:22', '10:20', '10:18', '10:16', '10:14', '10:11', 
 '10:09', '10:07', '10:05', '10:03', '10:01', '09:59', '09:57', '09:55', 
 '09:53', '09:50', '09:48', '09:46', '09:44', '09:42', '09:40', '09:38', 
 '09:36', '09:34', '09:32', '09:29']

1 个答案:

答案 0 :(得分:0)

列表切片更为宽松-如果列表中没有包含您要查询的元素,它甚至可以工作,在这种情况下,它将返回一个空列表[]。 在不存在的位置索引到列表中将返回错误。

可复制者:

tata = [] 

print  tata[0:200] 
try:
    print tata[0] 
except IndexError as idxerr:
    print idxerr 

输出:

[]
list index out of range

有关Introduction的部分,请参见Strings

word = 'Python'
     

尝试使用太大的索引会导致错误:

word[42]  # the word only has 6 characters Traceback (most recent call last):   
    File "<stdin>", line 1, in <module> IndexError: string
    index out of range 
     

但是,处理超出范围的切片索引       用于切片时优雅地显示:

word[4:42] 'on'
word[42:] ''

如果您需要访问列表的第一个和最后一个元素,则可以考虑执行以下操作:

firstVal, lastVal = above_temp[0:1],above_temp[-1:] # both wont throw error, but 
                                                    # might be [] afterwards

演示:

tata = [2,3]
firstVal, lastVal = tata[0:1],tata[-1:] 
print firstVal , lastVal

tata = []
firstVal, lastVal = tata[0:1],tata[-1:] 
print firstVal , lastVal

输出:

[2] [3]
[] []