Python 词典中的最低价
这是一个后续问题。我知道如何使用Python 词典中的最低价,python,Python,这是一个后续问题。我知道如何使用remove(min())删除列表中的最小值,但不知道如何使用字典。我正在尝试删除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 : s
remove(min())
删除列表中的最小值,但不知道如何使用字典。我正在尝试删除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]))
逻辑与从您提到的列表中删除值相同<代码>商店[商店]本身就是一个列表,在您的案例中也是如此。所以你在列表上所做的,也适用于这里
按照Lattyware的建议,一种更快更干净的方法是:
for prices in shops.values():
prices.remove(min(prices))
或:
如果最低价格是唯一的,则上述所有解决方案都会起作用,但如果列表中有多个最低值需要删除,则可以使用以下构造
{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还是只删除其中一个?请注意,这有点奇怪,因为您在键上循环,但您需要值<代码>用于商店中的价格。值():,价格。删除(最小(价格))
将更短、更清晰、更快。@Lattyware是的,您完全正确。谢谢我没有提到这一点,因为在当时的另一份答复中已经提到了。
{k : [e for e in v if e != min(v)] for k, v in shops.items()}
>>> 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]}
>>>