我需要通過其屬性之一保存資料類物件,如果鍵存在,則user_id經常查詢user_id并洗掉它。所述UserInfo類的定義如下:
@dataclass(frozen=True)
class UserInfo:
user_id: int
book: str
bookshelf_color: str
money: int
size: int
# operation for this data structure D
if user_id in D:
del D[user_id]
到目前為止,我只能想到使用內置的dict()(或在 Python3 中輸入的字典)來存盤它:user_id作為鍵,UserInfo物件作為值。所以洗掉使用del關鍵字(或pop?不確定哪個更好/Pythonic)。但我想知道是否有更有效的解決方案?
uj5u.com熱心網友回復:
當你需要一個集合并通過一個鍵查詢它時,沒有比使用 dict 更好的方法來解決它
關于del vs pop,既然你說密鑰并不總是存在,我會選擇pop,但你總是可以使用del并將其包裝在try/except中
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/347800.html
標籤:Python 蟒蛇-3.x 字典 系统 python-数据类
上一篇:使用串列和資料框從a創建字典
下一篇:在嵌套字典python中計數
