簡體   English   中英

Python:如何從字典中隨機選擇的鍵中獲取值

[英]Python: How to get a value from randomly selected key in a dictionary

我在這里要做的是從列表中隨機選擇

races = ['Dragonborn', 'Dwarf', 'Elf', 'Gnome', 'Half-Elf', 'Halfling', 'Half-Orc', 'Human', 'Tiefling']
races_choice = random.choice(races)

然后使用列表中的隨機選擇來查看單獨字典中的鍵

subraces = {
'Dwarf': ['Hill Dwarf', 'Mountain Dwarf'],
'Elf': ['High Elf', 'Wood Elf', 'Dark Elf'], 
'Halfling': ['Lightfoot', 'Stout'], 
'Gnome': ['Forest Gnome', 'Rock Gnome'],
}

如果該鍵與隨機選擇匹配,則從該鍵中打印一個隨機值。

我已經嘗試了一些事情,但我目前正在做的是:

if races_choice == subraces.keys():
    print(random.choice(subraces.values[subraces.keys]))

但這沒有任何回報。 我對如何做到這一點有點不知所措。

謝謝你。

您可以簡單地在字典上使用.get

DEFAULT_VALUE = "default value"
subraces = {
       'Dwarf': ['Hill Dwarf', 'Mountain Dwarf'],
       'Elf': ['High Elf', 'Wood Elf', 'Dark Elf'], 
       'Halfling': ['Lightfoot', 'Stout'], 
       'Gnome': ['Forest Gnome', 'Rock Gnome'],
}

races = ['Dragonborn', 'Dwarf', 'Elf', 'Gnome', 'Half-Elf', 
        'Halfling', 
        'Half-Orc', 'Human', 'Tiefling']

races_choice = random.choice(races)
subrace_options = subraces.get(races_choice, DEFAULT_VALUE)
if subrace_options != DEFAULT_VALUE:
    index = random.randint(0, (len(subrace_options) - 1))
    print(subrace_options[index])
else: 
    print("No subrace for specified race")

這將產生來自給定種族的子種族的名稱,例如對於Dwarf ,output 將是列表中的隨機條目,即Hill Dwarf

.get中的字符串值是默認值,如果在子種族的 map 中找不到密鑰(隨機選擇),則將分配該值。

似乎您可以根據鍵簡單地設置一個隨機 int 等效於項目的長度

import random

races = ['Dragonborn', 'Dwarf', 'Elf', 'Gnome', 'Half-Elf', 'Halfling', 'Half-Orc', 'Human', 'Tiefling']

races_choice = random.choice(races)

subraces = {
'Dwarf': ['Hill Dwarf', 'Mountain Dwarf'],
'Elf': ['High Elf', 'Wood Elf', 'Dark Elf'],
'Halfling': ['Lightfoot', 'Stout'],
'Gnome': ['Forest Gnome', 'Rock Gnome']}

if races_choice in subraces:
    print(subraces[races_choice][random.randint(0, len(subraces[races_choice]) - 1)])  # -1 since lists starts from 0, not 1
else:
    print('"' + races_choice + '"', 'has no subraces')

你也可以嘗試這樣的事情:

from random import choice

print(choice(subraces.get(choice(races),[0])) or 'no matches')

暫無
暫無

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

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