我正在向一個類添加一個函式以輸出價格最低的專案,但我得到的是所有價格。見照片和代碼。我在代碼上遺漏了什么?
def get_low_price(self):
self.get_total_toys()
#To check if toybox is empty or not
if self.total > 0:
msg = f'The toy box contains {self.total} toys\n'
for a_toy in self.all_toys:
self.get_total_cost()
msg = f'A {(a_toy.colour).lower()} {a_toy.name} which cost ${a_toy.price:.2f}\n'
for i in [a_toy.price]:
i = ([i])
print(min(i))
return f'{msg}Total cost: ${self.cost_total:.2f}'
uj5u.com熱心網友回復:
這個內部回圈沒有做任何有用的事情:
for i in [a_toy.price]:
i = ([i])
print(min(i))
這里a_toy已經只是一個玩具了。回圈一個只包含它的價格的新串列并不能完成任何你可以通過a_toy.price直接訪問獲得的東西,并且將回圈變數重新系結i到另一個新串列(在無關的括號中)不會添加任何東西。
我認為你想將所有尋找最小值的邏輯移到前面的回圈之外,除非你想自己比較價格。相反,您可以min在回圈之外只使用一個呼叫:
for a_toy in self.all_toys: # don't include the stuff below in this loop
...
cheapest = min(self.all_toys, key=lambda t: t.price) # find cheapest
# do something down here with cheapest, or cheapest.name, maybe
uj5u.com熱心網友回復:
我不明白您在該方法中使用 for 回圈到底想做什么。如果您認為i = ([i])將價格附加到串列中,那么這是錯誤的。使用以下邏輯并重寫您的方法。它會起作用的。
toys = {"doll": 5, "hulk": 10, "teddy": 15}
cheapest_toy_name = ""
cheapest_toy_price = float("inf")
for k, v in toys.items():
if cheapest_toy_price > v:
cheapest_toy_price = v
cheapest_toy_name = k
print(cheapest_toy_name)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/486735.html
上一篇:郵遞員:如何在使用JS回圈時向dateTime添加分鐘?
下一篇:回傳回圈wordpress
