简体   繁体   English

如何在Python中修复动态列表索引超出范围

[英]How to fix dynamic list index out of range in Python

We're working on a Python project, where we are updating 2 lists and then we subtract the elements on one list with elements from the other list. 我们正在研究一个Python项目,在这里我们要更新2个列表,然后用另一个列表中的元素减去一个列表中的元素。 Example of the 2 lists: 2个列表的示例:

list_station_temp = {25.0, 24.8, 24.9}
list_lpn_temp = {25.2, 24.5, 24.8}

Unfortunately for us the lists updates dynamically every 20 minutes with Crontab, which means that sometimes the length of the 2 list varies, so for example length of the lists can be different: 不幸的是,列表使用Crontab每20分钟动态更新一次,这意味着有时2个列表的长度会有所不同,例如,列表的长度可以不同:

Sometimes len(list_lpn_temp) = 3 and len(list_station_temp) = 2 and when we attempt to subtract the lists with each other we receive an index out of range 有时len(list_lpn_temp) = 3 and len(list_station_temp) = 2 ,当我们尝试相互减去列表时,会收到超出范围的索引

list_lpn_temp = []
list_station_temp = []
new_list_lpn_temp = []
list_lpn_WL = []
list_lpn_validated = []

for x in 3:
    a_temp = pd.read_sql('SELECT temperature FROM Raw_Data', conn).astype(float).values
    c_temp = pd.read_sql('SELECT temperature1m FROM Weather_Station', conn).astype(float).values

    list_lpn_temp.extend(a_temp)
    list_station_temp.extend(c_temp)

for i in range (len(list_lpn_temp)):
    WeLP = list_station_temp[i]-list_lpn_temp[i] #THIS IS WHERE THE INDEX OUT OF RANGE OCCURS
    if min_tol < WeLP < max_tol:
        validated_lpn = 1
        list_lpn_validated.append(validated_lpn)
        new_list_lpn_temp.extend(list_lpn_temp[i])
        list_lpn_WL.extend(WeLP)
    else:
        validated_lpn = 0
        list_lpn_WL.extend(WeLP)
        list_lpn_validated.append(validated_lpn)
        new_list_lpn_temp.extend(None)

How can we prevent the index out of range? 如何防止索引超出范围? We have a clue that for zip might work, but we're not sure how to implement this. 我们知道zip可能有效,但是我们不确定如何实现。 All help are appreciated! 感谢所有帮助!

WeLP = list_station_temp[i]-list_lpn_temp[i]

Above line of code is where the index out of range occurs 代码行上方是索引超出范围的位置

UPDATED CODE 更新的代码

list_lpn_temp = []
list_station_temp = []
new_list_lpn_temp = []
list_lpn_WL = []
list_lpn_validated = []

dict_temperature = {}

for x in 3:
    a_temp = pd.read_sql('SELECT temperature FROM Raw_Data', conn).astype(float).values
    c_temp = pd.read_sql('SELECT temperature1m FROM Weather_Station', conn).astype(float).values

    if a_temp:
        list_lpn_temp.extend(a_temp)
    else: 
        list_lpn_temp.append(float('nan'))

    if c_temp:
        list_station_temp.extend(c_temp)
    else: 
        list_station_temp.append(float('nan'))

for temp in dict_temperature:
    WeLP.append(dict_temperature[temp]['station'] - dict_temperature[temp]['lpn'])
    print (f'WeLP = {WeLP}')
    if min_tol < WeLP < max_tol:
        validated_lpn = 1
        list_lpn_validated.append(validated_lpn)
        new_list_lpn_temp.extend(list_lpn_temp[i])
        list_lpn_WL.extend(WeLP)
    else:
        validated_lpn = 0
        list_lpn_WL.extend(WeLP)
        list_lpn_validated.append(validated_lpn)

ERROR RECEIVING AFTER UPDATING: 更新后收到错误:

  Traceback (most recent call last):
  File "compareTemp.py", line 129, in <module>
    print(f'DICT_TEMPERATURE_STATION = {dict_temperature[temp]["station"]}')
TypeError: list indices must be integers or slices, not str

Have you tried the set operation subtract in python ? 您是否尝试过在python中进行设置操作减法? I think your use case would work suffice with that approach. 我认为您的用例可以满足该方法。

>>> list_a = [1,2,3,4]
>>> list_b = [3,4,5,6,7]
>>>
>>> set(list_a) - set(list_b)
set([1, 2])
>>>

The output is a set, which you can convert to a list using the list method. 输出是一个集合,您可以使用list方法将其转换为list

this_is_a_list = []
this_is_a_dict = {}

Have you considered maybe instead of using two separate lists you could use a single dict to do the same thing? 您是否考虑过可以使用一个字典来做同一件事,而不是使用两个单独的列表?

temperatures = {
    1: {
        'station': 25.0,
        'lpn': 25.2
    },
    2: {
        'station': 24.8,
        'lpn': 24.5
    },
    3: {
        'station': 24.9,
        'lpn': 24.8
    }
}

WeLP = []

for temp in temperatures:
    WeLP.append(temperatures[temp]['station'] - temperatures[temp]['lpn'])

print(WeLP)

Output is: 输出为:

[-0.1999999999999993, 0.3000000000000007, 0.09999999999999787]

When adding to the dict, if a temp does not exist then add it as null and then handle the error. 在添加到dict时,如果不存在temp,则将其添加为null,然后处理错误。 I think the way you are doing it you would be subtracting one result from another incorrectly (eg if a value is not collected) if I understand what you want correctly. 我认为,如果我正确理解了您想要的内容,那么您将错误地从另一个结果中减去一个结果(例如,如果未收集值)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM