簡體   English   中英

如何從字典中的列表之一中隨機選擇一項,並獲取列表的鍵?

[英]How do I randomly pick an item from one of the lists inside a dictionary, and also get the key for the list?

我有一個列表字典:

lists=dict(animals=["dog","cat","shark"],
           things=["desk","chair","pencil"],
           food=["spaghetti","ice-cream","potatoes"])

如何讓Python從列表中的一個中隨機選擇一個項目並告訴我它在哪個列表中? 或者如何從字典中選擇一個鍵,然后從對應於該鍵的列表中選擇一個值?

例如:

dog - from animals
potatoes - from food

random.choice從序列中選擇一個隨機項目:

import random

選擇要從dict繪制的鍵,您將其命名為lists

which_list = random.choice(lists.keys())

然后,使用該鍵從dict獲取list

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')對的一個列表('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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM