簡體   English   中英

從字典中存在的列表中刪除項目

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM