这是一个后续问题。我知道如何删除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