我试图运行一个列表并删除不满足某个阈值的元素,但是当我试图删除时,我收到错误'float' object does not support item deletion
。在
为什么我得到这个错误?有没有办法从这样的列表中删除浮动项?在
相关代码:
def remove_abnormal_min_max(distances, avgDistance):
#Define cut off for abnormal roots
cutOff = 0.20 * avgDistance # 20 percent of avg distance
for indx, distance in enumerate(distances): #for all the distances
if(distance <= cutOff): #if the distance between min and max is less than or equal to cutOff point
del distance[indx] #delete this distance from the list
return distances
您的
float
值的list
称为distances
(复数),该序列中的每个float
值称为distance
(单数)。在你试图使用后者,而不是前者。}对象。在
del distance[indx]
失败,因为这是float
值,而不是{您只需添加缺少的
s
:但是,现在您正在原地修改列表,并在循环时缩短它。这将导致您错过元素;曾经位于
i + 1
的项现在位于i
,而迭代器则愉快地继续位于i + 1
。在解决此问题的方法是使用您希望保留的所有内容构建一个新的列表对象:
^{pr2}$您在评论中提到需要重用已删除距离的索引。您可以使用列表理解功能立即生成所需的所有
indx
的列表:然后您可以在这个新列表上进行迭代,以完成您需要的其他工作:
^{pr2}$你也可以将你的其他工作归纳为另一个清单理解:
另外,如果您正在使用NumPy,这是一个面向Python的数值和科学计算包,那么您可以利用boolean数组以及它们所称的smart indexing,并直接使用
indxs
访问列表:相关问题 更多 >
编程相关推荐