所以我在玩弄這段代碼:
def cheapest_shark(prices: List, sharks: List ) -> Tuple:
shp = zip(sharks, prices)
sharkprices = tuple(shp)
print(sharkprices)
我的輸入是
cheapest_shark([230, 180, 52, 390, 520], [1, 0, 0, 1, 1])
(每個數字在輸出中相互連接:(230, 1) (180, 0) 等等)
我試圖以這樣一種方式創建函式,它總是回傳元組中最小的專案(但它需要有一個 1)。所以在這種情況下,輸出需要是 (230,1)。我嘗試將它轉換為字典,然后制作一個 for 回圈,檢查是否有 1 作為值,然后取剩余專案的最低總和,但這對我來說沒有用。有沒有人對我如何使這個功能起作用有任何建議?
uj5u.com熱心網友回復:
嘗試過濾元組(只保留 shark 為 1 的值)并使用min():
def cheapest_shark(prices, sharks):
shp = ((p, s) for p, s in zip(prices, sharks) if s == 1)
return min(shp, default=None)
x = cheapest_shark([230, 180, 52, 390, 520], [1, 0, 0, 1, 1])
print(x)
印刷:
(230, 1)
注意:如果沒有任何值為 1 的元組,default=則回傳該值(在本例中為None)。沒有default=引數會拋出例外。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/534505.html
標籤:Python字典元组
上一篇:將字典中的專案放入字串中
