我有一个列表字典:
lists=dict(animals=["dog","cat","shark"],
things=["desk","chair","pencil"],
food=["spaghetti","ice-cream","potatoes"])
如何让 Python 从其中一个列表中随机选择一个项目并告诉我它在哪个列表中?或者我如何从字典中选择一个键,然后从与该键对应的列表中选择一个值?
例如:
狗 - 来自动物 土豆——来自食物
我有一个列表字典:
lists=dict(animals=["dog","cat","shark"],
things=["desk","chair","pencil"],
food=["spaghetti","ice-cream","potatoes"])
如何让 Python 从其中一个列表中随机选择一个项目并告诉我它在哪个列表中?或者我如何从字典中选择一个键,然后从与该键对应的列表中选择一个值?
例如:
狗 - 来自动物 土豆——来自食物
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])
我可以立即想到的两种方法:
('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)