float'对象不支持项删除
我正在尝试遍历一个列表,删除那些不符合某个标准的元素,但当我试图删除时,出现了错误 '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
2 个回答
1
你在评论中提到需要重新使用被删除的距离的索引。你可以通过列表推导式一次性创建一个包含所有需要的 indx
的列表:
indxs = [k for k,d in enumerate(distances) if d <= cutOff]
然后你可以遍历这个新列表,完成你需要的其他工作:
for indx in indxs:
del distances[indx]
del otherlist[2*indx, 2*indx+1] # or whatever
你也可以把其他的工作整理成另一个列表推导式:
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的数值和科学计算的库,你可以利用布尔数组和他们所说的 智能索引,直接用 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
2
你的 float
值列表叫做 distances
(复数),而这个列表里的每一个单独的 float
值叫做 distance
(单数)。
你试图使用后者,也就是单个的 distance
,而不是前者 distances
。使用 del distance[indx]
会失败,因为你是在操作一个 float
值,而不是列表对象。
你只需要加上缺少的 s
就可以了:
del distances[indx]
# ^
不过,现在你是在 原地 修改这个列表,也就是在循环的时候让它变短。这会导致你漏掉一些元素;原本在位置 i + 1
的项目现在变成了位置 i
,而迭代器却还在 i + 1
继续前进。
解决这个问题的方法是创建一个新的列表,把你想保留的所有内容放进去:
distances = [d for d in distances if d > cutOff]