简体   繁体   English

从字典中选择随机值

[英]Selecting random values from dictionary

Let's say I have this dictionary: 假设我有这本词典:

dict = {'a': 100, 'b': 5, 'c': 150, 'd': 60};

I get the key which has greatest value with this code: 我得到了这个代码具有最大价值的密钥:

most_similar = max(dic.iteritems(), key=operator.itemgetter(1))[0]

it returns 'c' 它返回'c'

But I want to select a random key from top 3 greatest values. 但我想从前3个最大值中选择一个随机密钥。 According to this dictionary top 3 are: 根据这本词典,前三名是:

c
a
d

It should randomly select a key from them. 它应该从中随机选择一个键。 How can I do that? 我怎样才能做到这一点?

If you want to find the top 3 keys and then get one of the keys randomly, then I would recommend using random.choice and collections.Counter , like this 如果你想找到前3个键,然后随机获得其中一个键,那么我建议使用random.choicecollections.Counter ,就像这样

>>> d = {'a': 100, 'b': 5, 'c': 150, 'd': 60}
>>> from collections import Counter
>>> from random import choice
>>> choice(Counter(d).most_common(3))[0]
'c'

Counter(d).most_common(3) will get the top three values from the dictionary based on the values of the dictionary object passed to it and then we randomly pick one of the returned values and return only the key from it. Counter(d).most_common(3)将根据传递给它的字典对象的值从字典中获取前三个值,然后我们随机选择一个返回的值并仅返回其中的键。

Get the keys with the three largest values. 获取具有三个最大值的键。

>>> import heapq
>>> d = {'a': 100, 'b': 5, 'c': 150, 'd': 60}
>>> largest = heapq.nlargest(3, d, key=d.__getitem__)
>>> largest
['c', 'a', 'd']

Then select one of them randomly: 然后随机选择其中一个:

>>> import random
>>> random.choice(largest)
'c'

Sort the dictionary by descending value, get the first three objects from the resulting list , then use random.choice : 按降序对字典排序,从结果list获取前三个对象,然后使用random.choice

>>> import random
>>> d = {'a': 100, 'b': 5, 'c': 150, 'd': 60}
>>> random.choice(sorted(d, reverse=True, key=d.get)[:3])
'c'

And don't call it dict or you'll mask the built-in. 并且不要把它称为dict否则你将掩盖内置的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM