![](/img/trans.png)
[英]How would you delete a random key from a dictionary, but ONLY if the item has a certain value?
[英]How do I pull a random key from a dictionary with a certain value?
我有一本单词词典,每个单词都有一定的分值。 我会在字典中搜索具有特定点值的随机词,即找到一个点值为 3 的随机词。我的字典结构如下:
wordList = {"to":1,"as":1,"be":1,"see":2,"bed":2,"owl":2,"era":2,"alive":3,"debt":3,"price":4,"stain":4} #shortened list obviously
在网上四处寻找,我找不到很好的答案,或者我找到了,但我只是不太明白。
我会使用带有列表理解的random.choice()
:
from random import choice
choice([word for word, count in wordList.items() if count == 3])
如果您不关心性能,那会起作用,但每次访问它时都会重新创建一个字典:
random.choice([k for k,v in wordList.items() if v == 3])
否则最好创建一个反向字典,以节省多次运行的时间:
from random import choice
from collections import defaultdict
rev = defaultdict(list)
for k, v wordList.items():
rev[v].append(k)
...
choice(rev[3])
我认为使用if statement
和random.choice
可以在短时间内解决您的问题
from random import choice
wordList = {"to": 1, "as": 1, "be": 1, "see": 2, "bed": 2, "owl": 2, "era": 2,
"alive": 3, "debt": 3, "price": 4, "stain": 4} # shortened list obviously
value = int(input())
lst = []
for key,val in wordList.items():
if val == value:
lst.append(key)
print(choice(lst))
单线:
choice([key for key, val in wordList.items() if val == value])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.