从列表中的列表中删除项目

时间:2014-07-21 00:51:43

标签: python list dictionary

inventory = {
        'gold' : [500,50],
        'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
        'backpack' : ['xylophone','dagger', 'bedroll','bread loaf'].sort(),'pocket':      ['seashell','strange berry','lint']
}

用于删除存储在'backpack'键中的列表中的'dagger',我试过:

del(inventory['backpack'][1])

inventory['backpack'].remove(1)

inventory['backpack'].remove(["backpack"][1])

但是错误

Traceback (most recent call last):
  File "python", line 6, in <module>
AttributeError: 'NoneType' object has no attribute 'remove'

我该怎么办?

3 个答案:

答案 0 :(得分:1)

['xylophone','dagger', 'bedroll','bread loaf'].sort()

返回None。因此,'NoneType'对象没有属性'remove'

sorted(['xylophone','dagger', 'bedroll','bread loaf'])

代替。

答案 1 :(得分:1)

因为您将'backpack'设置为:

['xylophone','dagger', 'bedroll','bread loaf'].sort()

.sort()对列表就地进行排序并返回None。因此inventory['backpack']None

在构建库存后对列表进行排序:

inventory = ...
inventory['backpack'].sort()

或使用sorted

'backpack': list(sorted(['xylophone', 'dagger', 'bedroll', 'bread loaf'])),

答案 2 :(得分:0)

.sort()不会以这种方式工作,它会更改列表但返回None

x = ['c', 'b', 'a']
x.sort()
print(x)

此代码将输出['a', 'b', 'c'],但此代码将输出None

x = ['c', 'b', 'a']
x = x.sort()
print(x)

要解决此问题,您必须将代码更改为:

backpack = ['xylophone','dagger', 'bedroll','bread loaf']
backpack.sort()
inventory = {
        'gold' : [500,50],
        'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
        'backpack' : backpack,'pocket':      ['seashell','strange berry','lint']
}

或者:

inventory = {
        'gold' : [500,50],
        'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
        'backpack' : sorted(['xylophone','dagger', 'bedroll','bread loaf']),'pocket':      ['seashell','strange berry','lint']
}