浮动对象不支持项目删除

2024-10-02 18:22:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图运行一个列表并删除不满足某个阈值的元素,但是当我试图删除时,我收到错误'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

Tags: the元素列表forif错误阈值min
2条回答

您的float值的list称为distances(复数),该序列中的每个float值称为distance(单数)。在

你试图使用后者,而不是前者。del distance[indx]失败,因为这是float值,而不是{}对象。在

您只需添加缺少的s

del distances[indx]
#           ^

但是,现在您正在原地修改列表,并在循环时缩短它。这将导致您错过元素;曾经位于i + 1的项现在位于i,而迭代器则愉快地继续位于i + 1。在

解决此问题的方法是使用您希望保留的所有内容构建一个新的列表对象:

^{pr2}$

您在评论中提到需要重用已删除距离的索引。您可以使用列表理解功能立即生成所需的所有indx的列表:

indxs = [k for k,d in enumerate(distances) if d <= cutOff]

然后您可以在这个新列表上进行迭代,以完成您需要的其他工作:

^{pr2}$

你也可以将你的其他工作归纳为另一个清单理解:

indxs = [k for k,d in enumerate distances if d > cutOff] # note reversed logic
distances = [distances[indx] for indx in indxs] # one statement so doesn't fall in the modify-as-you-iterate trap
otherlist = [otherlist[2*indx, 2*indx+1] for indx in indxs]

另外,如果您正在使用NumPy,这是一个面向Python的数值和科学计算包,那么您可以利用boolean数组以及它们所称的smart indexing,并直接使用indxs访问列表:

import numpy as np
distances = np.array(distances) # convert to a numpy array so we can use smart indexing
keep = ~(distances > cutOff)
distances = distances[keep] # this won't work on a regular Python list

相关问题 更多 >