[英]Remove item from list that present in 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']
}
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'
['xylophone','dagger', 'bedroll','bread loaf'].sort()
返回無。 因此,“ NoneType”對象沒有屬性“刪除”
嘗試
sorted(['xylophone','dagger', 'bedroll','bread loaf'])
代替。
因為您為此設置了'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'])),
.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']
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.