gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:40:13 26 4
gpt4 key购买 nike

我们正在开发一个 Python 项目,其中我们正在更新 2 个列表,然后用另一个列表中的元素减去一个列表中的元素。 2 个列表的示例:

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

对我们来说不幸的是,列表使用 Crontab 每 20 分钟动态更新一次,这意味着有时 2 个列表的长度会有所不同,例如列表的长度可能不同:

有时 len(list_lpn_temp) = 3 和 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)

如何防止索引超出范围?我们有线索表明 for zip 可能有效,但我们不确定如何实现它。感谢所有帮助!

WeLP = list_station_temp[i]-list_lpn_temp[i]

上面这行代码是索引超出范围的地方

更新代码

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)

更新后接收错误:

  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

最佳答案

你尝试过Python中的set运算减法吗?我认为您的用例足以满足这种方法。

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

输出是一个集合,您可以使用 list 方法将其转换为列表。

关于python - 如何修复Python中的动态列表索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57756241/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com