问题描述
我需要帮助,在python中找到一种方法来获取多维python词典中的最大N
个项目.例如:
I need help finding a way in python to get the max N
items in a multi-dimensional python dictionary. For example:
things = {
"car": { "weight": 100 },
"apple": { "weight": 1 },
"spanner": { "weight": 10 }
}
在这种情况下,我想在词典中找到2个权重最高的项目,特别是这些项目的键.因此,在这种情况下,它应该返回["car", "spanner"]
In this case, I would want to find the 2 highest-weighted items in the dictionary, specifically the keys of these items. So in this case, it should return ["car", "spanner"]
注意:这是我第一次尝试遗传算法,因此我可能做得不正确.完全没有.
因为我是英国人,所以我正在寻找我能想象的最好的茶,所以我正在编写一个python程序,该程序生成10个随机的茶,然后使用自然选择在这10个茶中排名前5位,依此类推上.
As I am British, I am searching for the best cup of tea I can imagine, so I am writing a python program that generates 10 random cups of tea, then uses natural selection to find the top 5 in that ten and so on.
将一杯茶建模为python字典,具有5个键:
A cup of tea is modelled as a python dictionary, with 5 keys:
{
"brew_time": Some Number,
"milk": Some Number,
"sweeteners": Some Number,
"fitness": Some Number (This is what I'm interested in),
"name": Some randomly generated name (Doesn't really matter)
}
我的程序将吐出的一杯茶看起来像这样:
A cup of tea my program will spit out will look something like this:
{'brew_time': 2.0, 'milk': 0.5, 'sweeteners': 3.0, 'name': 'bold cup', 'fitness': 0}
然后生成10杯茶,存储在teas
变量中.这是该输出的示例:
It then generates 10 cups of tea, stored in the teas
variable. This is an example of an output of that:
{0: {'brew_time': 2.0, 'milk': 0.4, 'sweeteners': 1.0, 'name': 'unafraid brew', 'fitness': 0}, 1: {'brew_time': 3.0, 'milk': 0.5, 'sweeteners': 3.0, 'name': 'fire-eating blend', 'fitness': 0}, 2: {'brew_time': 2.0, 'milk': 0.6, 'sweeteners': 2.0, 'name': 'fearless drink', 'fitness': 0}, 3: {'brew_time': 2.0, 'milk': 0.9, 'sweeteners': 3.0, 'name': 'fire-eating blend', 'fitness': 0}, 4: {'brew_time': 2.0, 'milk': 0.8, 'sweeteners': 2.0, 'name': 'fire-eating cuppa', 'fitness': 0}, 5: {'brew_time': 3.0, 'milk': 0.3, 'sweeteners': 1.0, 'name': 'fire-eating drink', 'fitness': 0}, 6: {'brew_time': 4.0, 'milk': 0.7, 'sweeteners': 2.0, 'name': 'dauntless medley', 'fitness': 0}, 7: {'brew_time': 3.0, 'milk': 0.3, 'sweeteners': 2.0, 'name': 'dauntless cuppa', 'fitness': 0}, 8: {'brew_time': 3.0, 'milk': 0.9, 'sweeteners': 2.0, 'name': 'epic drink', 'fitness': 0}, 9: {'brew_time': 2.0, 'milk': 0.4, 'sweeteners': 2.0, 'name': 'gusty drink', 'fitness': 0}}
我现在正在尝试编写一个名为selection()
的函数,该函数将从字典中删除5种最不适合的茶. (我可以使用rank_tea()
函数来设置茶的适应度,该函数采用一个数组并设置所有茶的适应度,该数字是介于0到1之间的数字,代表茶的质量)
I'm now trying to code a function called selection()
that will remove the 5 least fit teas from the dictionary. (The fitness of a tea is set by me, using the rank_tea()
function, which takes an array and sets all the teas fitnesses, which is a number between 0 - 1 that represents the quality of the tea)
这是我到目前为止所获得的,但是它不起作用:
This is what I've got so far, but it doesn't work:
def selection():
teaCopy = teas.copy()
fitnesses = []
for i in range(0, len(teaCopy)):
fitnesses.append(teas[i]["fitness"])
print(fitnesses)
max_fitnesses_indicies = sorted(range(len(fitnesses)), key=lambda x: fitnesses[x])
print(max_fitnesses_indicies)
len_array = []
print(len_array)
for i in range(0, len(teas)):
len_array.append(i)
to_be_del = list( set(max_fitnesses_indicies) - set(len_array) )
print(to_be_del)
完整的代码.很抱歉,我只是没有回答这个问题而已.不想错过任何事情.
This is the full code. Sorry for the length of the question, I just didn't want to miss anything.
任何帮助将不胜感激
推荐答案
您可以简单地使用:
>>> sorted(things.keys(),key=lambda x:things[x]['weight'],reverse=True)
['car', 'spanner', 'apple']
获得按重量排序的物品清单(此处按相反顺序,以便较重的物品先被排序).因此,如果您致电:
To obtain a list of items sorted by their weight (here in reversed order such that the more heavy things are sorted first). So if you call:
>>> sorted(things.keys(),key=lambda x:things[x]['weight'],reverse=True)[:2]
['car', 'spanner']
您得到两个最重的东西.但这将以 O(n log n) 运行.如果您希望获得的 k个值 k 很小(与总数相比).您可以使用heapq
:
you get the two heaviest. But this will run in O(n log n). In case the number of values k you wish to obtain is small (compared to the total number). You can use heapq
:
from heapq import nlargest
result = nlargest(k,things.keys(),key=lambda x:things[x]['weight'])
据我所知-以 O(n log k) ( k 选择).
这篇关于在Python字典中找到最大的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!