python-AttributeError:'NoneType'对象没有属性'remove'

时间:2017-10-23 19:00:53

标签: python

我在python中有一个3D列表,如:

features= [ [[1,2,3],[1,2,3],[1,2,3]] ,None , [[1,2,3],[1,2,3],[1,2,3]],
        [[1,2,3],[1,2,3],[1,2,3]], None,None,[[1,2,3],[1,2,3],[1,2,3]] ]

我希望看到:

features=[ [[1,2,3],[1,2,3],[1,2,3]] ,[[1,2,3],[1,2,3],[1,2,3]],
               [[1,2,3],[1,2,3],[1,2,3]] ,[[1,2,3],[1,2,3],[1,2,3]] ]

当我尝试使用以下代码删除None时:

for i in range(len(features)):
if features[i]==None:
    features[i].remove()

它产生错误:

  

AttributeError:'NoneType'对象没有属性'remove'

如果我试试这个:

for i in range(len(features)):
if features[i]==None:
    del features[i]

它产生错误:

  

ValueError:具有多个元素的数组的真值是不明确的。使用a.any()或a.all()

最后我尝试了这段代码:

for i in range(len(features)):
if features[i]==None:
    features[i]=filter(None,features[i])

它产生了错误: -

  

TypeError:'NoneType'对象不可迭代

如何解决此错误?

6 个答案:

答案 0 :(得分:0)

创建列表推导并仅在索引不是None时保留值,它将保持子列表的完整性:

features = [[[1, 2, 3], [1, 2, 3], [1, 2, 3]], None, [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], None, None, [[1, 2, 3], [1, 2, 3], [1, 2, 3]]]

>>> print features 
[[[1, 2, 3], [1, 2, 3], [1, 2, 3]], None, [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], None, None, [[1, 2, 3], [1, 2, 3], [1, 2, 3]]]

>>> print [f for f in features if f is not None]
[[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]]

答案 1 :(得分:0)

简短而简单:

features_x = list(filter(None, features))
print(features_x)

请参阅a demo on ideone.com

答案 2 :(得分:0)

在第一个代码块中,您没有传递要从列表中删除的值。在第二个代码块中,您在迭代时更改列表,从而产生偏斜的索引与值的位置。最好的方法是从列表中筛选出None

features= [ [[1,2,3],[1,2,3],[1,2,3]] ,None , [[1,2,3],[1,2,3],[1,2,3]],
    [[1,2,3],[1,2,3],[1,2,3]], None,None,[[1,2,3],[1,2,3],[1,2,3]] ]
final_features = list(filter(lambda x:x is not None, features))

输出:

[[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]]

答案 3 :(得分:0)

就像威廉说的那样,你永远不应该改变你正在迭代的列表。正确的做法是创建一个新列表。您可以通过以下方式使用列表推导来完成此操作。

 New = [item for item in mylist if item is not None]

答案 4 :(得分:0)

你也可以这样试试:

new_features = []

for f in features:
    if f is not None:
        new_features.append(f)

答案 5 :(得分:0)

您也可以在执行 features[i].remove() 时向后索引数组。

    for i in reversed(range(len(features))):
        if features[i]==None:
            features[i].remove()

这样您就不会从索引下方删除数组项。

毫无疑问,其他答案是灵活的代码,但这是最简单的简单代码解决方案。

当然,作为一般的最佳实践,您永远不应该更改您正在迭代的列表,但是当您绝对必须继续使用相同的列表时,这将起作用。