我有一份清单词典:
lists=dict(animals=["dog","cat","shark"],
things=["desk","chair","pencil"],
food=["spaghetti","ice-cream","potatoes"])
如何让Python从其中一个列表中随机选择一个项目并告诉我它所在的列表?或者我如何从字典中选择一个键,然后从与该键对应的列表中选择一个值?
例如:
dog - from animals potatoes - from food
答案 0 :(得分:4)
random.choice
从序列中选择一个随机项:
import random
从您dict
lists
中选择要绘制的密钥:
which_list = random.choice(lists.keys())
然后,使用该密钥从list
获取dict
:
item = random.choice(lists[which_list])
如果你需要相同的权重:
import random
which_list, item = random.choice([(name, value)
for name, values in lists.iteritems()
for value in values])
答案 1 :(得分:3)
我可以立即想到的两种方法:
('list-name','value')
对的列表(无论每个列表有多少条目,但需要更多内存,更容易获得统一分布权)做前者的一种方法:
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
(如果你不关心在列表之间进行统一分配:)
import random
list_name = random.choice(lists.keys())
chosen_item = random.choice(lists[list_name])
......和后一种方法:
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)
以及后者的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)