[英]How do I randomly pick an item from one of the lists inside a dictionary, and also get the key for the list?
I have a dictionary of lists: 我有一个列表字典:
lists=dict(animals=["dog","cat","shark"],
things=["desk","chair","pencil"],
food=["spaghetti","ice-cream","potatoes"])
How can I get Python to randomly pick an item from one of the lists and tell me what list it was in? 如何让Python从列表中的一个中随机选择一个项目并告诉我它在哪个列表中? Or how do I pick a key from the dictionary and then a value from the list corresponding to that key?
或者如何从字典中选择一个键,然后从对应于该键的列表中选择一个值?
For example: 例如:
dog - from animals potatoes - from food
random.choice
picks a random item from a sequence: random.choice
从序列中选择一个随机项目:
import random
Select the key to draw from your dict
, which you've named lists
: 选择要从
dict
绘制的键,您将其命名为lists
:
which_list = random.choice(lists.keys())
Then, use that key to get a list
from the dict
: 然后,使用该键从
dict
获取list
:
item = random.choice(lists[which_list])
If you need equal weighting: 如果需要相等的权重:
import random
which_list, item = random.choice([(name, value)
for name, values in lists.iteritems()
for value in values])
Two approaches I can think of right away: 我可以立即想到两种方法:
('list-name','value')
pairs (easier to get the uniform distribution right no matter how many entries there are per list, but requires more memory) ('list-name','value')
对的一个列表('list-name','value')
无论每个列表有多少个条目,都更容易获得统一的分配权,但是需要更多的内存) One way to do the former: 前一种方法:
from itertools import chain
import random
weight_choices = list(chain(*([name] * len(values) for (name, values) in lists.iteritems()))) # generate a list of the form ("animals", "animals", "animals", ...)
list_name = random.choice(weight_choice) # The list it's chosen from...
chosen_item = random.choice(lists[list_name]) # and the item itself
(and if you don't care about getting an uniform distribution between lists:) (如果您不在乎列表之间的均匀分布:)
import random
list_name = random.choice(lists.keys())
chosen_item = random.choice(lists[list_name])
... and the latter method: ...以及后一种方法:
from itertools import chain, repeat
all_items = list(chain(*((zip(repeat(name), values) for (name, values) in lists.iteritems()))))
list_name, chosen_item = random.choice(all_items)
and a less itertools
way for the latter: 而后者的
itertools
方法较少:
all_items = []
for name, values in lists.iteritems():
for value in values:
all_items.append((name, value))
list_name, chosen_item = random.choice(all_items)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.