![](/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.