這是一個後續問題。我知道如何刪除remove(min())
列表中的最小值,但不是字典。我試圖去掉Python中dictionarys的最低價格。Python在字典中的最低價格
shops['foodmart'] = [12.33,5.55,1.22]
shops['gas_station'] = [0.89,45.22]
這是一個後續問題。我知道如何刪除remove(min())
列表中的最小值,但不是字典。我試圖去掉Python中dictionarys的最低價格。Python在字典中的最低價格
shops['foodmart'] = [12.33,5.55,1.22]
shops['gas_station'] = [0.89,45.22]
具體而言,該示例給出:
shops['foodmart'].remove(min(shops["foodmart"]))
更一般地,爲整個詞典:
for shop in shops :
shops[shop].remove(min(shops[shop]))
邏輯是相同的,從中提列表中刪除值你懂。 shops[shop]
本身也是一個列表,以及你的情況。所以你在列表上做什麼,在這裏也適用。
一種更快和更清潔的方法通過Lattyware的建議將是:
for prices in shops.values():
prices.remove(min(prices))
請注意,這是有點奇怪,因爲你循環的鍵,但你想要的值。 '對於shops.values()中的價格:','price.remove(min(prices))''會更短,更清晰和更快。 –
@Lattyware是的,你是絕對正確的。謝謝。我沒有提到它,因爲那個時候它已經在另一個答案中。 – asheeshr
>>> shops={}
>>> shops['foodmart'] = [12.33,5.55,1.22]
>>> shops['gas_station'] = [0.89,45.22]
>>> shops
{'foodmart': [12.33, 5.55, 1.22], 'gas_station': [0.89, 45.22]}
>>> for x in shops: #iterate over key
shops[x].remove(min(shops[x])) # min returns the smallest value and
# that is passed to remove
>>> shops
{'foodmart': [12.33, 5.55], 'gas_station': [45.22]}
或:
>>> for values in shops.values(): #iterate over values
... values.remove(min(values))
...
>>> shops
{'foodmart': [12.33, 5.55], 'gas_station': [45.22]}
所有上述解決辦法如果最小价格是唯一的工作,但在如果列表中有多個最小值需要刪除,則可以使用以下構造
{k : [e for e in v if e != min(v)] for k, v in shops.items()}
這裏需要特別注意的是,使用list.remove實際上會從列表中刪除第一個項目,它與針頭(又稱最小值)相匹配,但是要一次去除所有分鐘,您必須重建列表過濾與最小值匹配的所有項目。 注意,這將是比使用list.remove慢,但最後你要決定什麼是您的要求
不幸的是,雖然上述結構很簡潔,但它最終調用min
爲每個每個價格因素店。您可能不想將其翻譯爲循環結構以減少開銷
>>> for shop, price in shops.items():
min_price = min(price)
while min_price in price:
shops[shop].remove(min_price)
>>> shops
{'foodmart': [12.33], 'toy_store': [15.32], 'gas_station': [45.22], 'nike': [69.99]}
>>>
如果列表具有相同的最低價格兩次,您希望發生什麼? '[1.0,1.0,2.0,5.0]'?是否應該刪除1個或只有其中一個? – DSM