如何解决函数返回的元组不可下标
我编写了一个函数,它接受一个值和一个列表。该函数查看该值位于列表的哪两个值之间;并返回一个具有上下位置的元组。
如果我用单个值调用我的函数,我可以对结果元组进行下标。但是,如果我将函数放入多次调用它的 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 数组中的第一个值小于您的最小限制。
当你得到一个太小的值时,我不知道你期望返回什么,所以不可能说如何解决它。
,需要处理value小于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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。