我有2節課。AlchemicalStorage 類用于存盤 AlchemicalElement 物件。
class AlchemicalElement:
def __init__(self, name: str):
self.name = name
def __repr__(self):
return f'<AE: {self.name}>'
class AlchemicalStorage:
def __init__(self):
self.storage_list = []
我已經有一個向 AlchemicalStorage 添加元素的功能。我需要的是一個可以概述存盤內容的功能。
到目前為止我所擁有的:
def get_content(self) -> str:
"""
Return a string that gives an overview of the contents of the storage.
Example:
storage = AlchemicalStorage()
storage.add(AlchemicalElement('Fire'))
storage.add(AlchemicalElement('Water'))
storage.add(AlchemicalElement('Water'))
print(storage.get_content())
Output:
Content:
* Fire x 1
* Water x 2
The elements must be sorted alphabetically by name.
"""
count = {}
for e in self.storage_list:
if e not in count:
count[e] = 1
else:
count[e] = 1
這個想法是我想創建一個字典,其中鍵作為元素,值作為數量。但我得到的不是簡單的“火”,而是我所做的表示(<AE: Fire>)。
問題是:有沒有辦法擺脫“<AE:>”?或者也許有一種更簡單的方法來撰寫這個函式而不創建字典?
另外,我希望有一個如何實作輸出字串的示例。
uj5u.com熱心網友回復:
聽起來有點像您想要列印出AlchemicalStorage具有特定格式的內容,因此您可以在__str__方法中創建該格式:
from collections import Counter
class AlchemicalStorage:
def __str__(self):
# a Counter will definitely be useful for what you are trying to do
lines = []
for item, count in Counter(self.storage_list).items():
lines.append(f"* {item.name} x {count}")
return "Contents:\n" "\n".join(lines)
這里的主要內容是,您可以直接訪問該欄位以僅顯示專案名稱,而不是依賴__repr__具有您不感興趣的格式的方法。.name
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/530868.html
標籤:Python列表字典哎呀
上一篇:從具有條件的元組中提取串列
