函数返回的元组不可下标



我写了一个函数,它接受一个值和一个列表。该函数查找该值位于列表的哪两个值之间;并返回一个包含上下位置的元组。

如果我用单个值调用函数,我可以将结果元组下标。然而,如果我把我的函数放在for循环中,并多次调用它,它会给我以下错误:'NoneType'对象是不可下标的。

我是Python新手。我将感激任何帮助。也许可以用一种更有效的方式来编码。

注意:yearFractions是一个NumPy数组,其元素中包含浮点数。

代码:

import numpy as np
yearFractions = np.array([0.22777778, 0.47777778, 0.73333333, 0.98888889, 1.24166667, 1.49166667, 1.74722222])
vertices = {0.25 : 0,
0.5 : 0,
1 : 0,
2 : 0,
3 : 0,
4 : 0,
5 : 0,
10 : 0,
15 : 0,
20 : 0,
30 : 0
}
#My function
def findPosition(value, valuesList):
lastIndex = len(valuesList) -1 
for i in range(len(valuesList)):
if value >= valuesList[i] and value < valuesList[i+1]:
return i, i+1
elif value > valuesList[lastIndex]:
return lastIndex-1, lastIndex
#Calling my function in a for loop
for i in yearFractions:
pos = findPosition(i, list(vertices.keys()))
print(pos[0])

在你的函数中:

def findPosition(value, valuesList):
lastIndex = len(valuesList) -1 
for i in range(len(valuesList)):
if value >= valuesList[i] and value < valuesList[i+1]:
return i, i+1
elif value > valuesList[lastIndex]:
return lastIndex-1, lastIndex

elif部分将在每次循环中求值,我认为您不希望这样做。此外,你的函数完全忽略了如果你的一个值小于valuesList中的最小值会发生什么。numpy数组中的第一个值小于最小值。

我不知道当你得到一个太小的值时,你希望返回什么,所以不可能说如何修复它。

您需要处理值小于valuesList中所有元素的情况。如果(假设valuesList按升序排序):

value < valuesList[0]

稍微修改一下代码,使其运行得更快

def findPosition(value, valuesList):
# if key list is not in ascending use "valuesList = valuesList.sort()"
if value > valuesList[-1]:                             # -1 to access last element
return len(valuesList), len(valuesList)            # given value greater then last value of list
else:
for idx, val in enumerate(valuesList):
if val>value and idx <= len(valuesList) - 1:     # given value is less then the current value of the list and index
break;                                         # break to stop the for loop when req value is reached
return idx, idx+1

最新更新