簡體   English   中英

如何從一個鍵有多個值的字典中獲取隨機鍵值對?

[英]How to get a random key-value pair from dictionary where there are many values to one key?

我正在嘗試使用random.sample() 返回一個隨機鍵值對,並只打印鍵,即fruits: papaya,但我的代碼返回一個TypeError。 如何解決? 謝謝!

import random

Dictionary = {"fruits": ["watermelon","papaya", "apple"], "buildings": ["apartment", "museum"], "mammal": ["horse", "giraffe"], "occupation": ["fireman", "doctor"]}


def choose_word():
    hint, chosen_word = random.sample(Dictionary.items(), 2)
    print("Hint: " + hint)
    blank = []
    for letter in chosen_word:
        blank.append("_")
    print("".join(blank))
    return chosen_word

錯誤信息

TypeError: can only concatenate str (not "tuple") to str

random.sample(Dictionary.items(), 2)從字典中返回兩個隨機鍵值對,因此hint成為您的第一個鍵值對,而chosen_word成為第二個。 因此,提示是('fruits', ['watermelon', 'papaya', 'apple']) 由於您無法連接字符串( "Hint: " )和元組( hint ),因此您會收到該錯誤。

你只想要一個鍵值對嗎? hint, chosen_word = random.sample(Dictionary.items(), 1)[0]

如果要打印一串下划線,鍵中每個單詞一個下划線,只需執行以下操作: print("_" * len(chosen_word))

所以,總的來說:

import random

Dictionary = {"fruits": ["watermelon","papaya", "apple"], 
              "buildings": ["apartment", "museum"], 
              "mammal": ["horse", "giraffe"], 
              "occupation": ["fireman", "doctor"]}

def choose_word():
    hint, chosen_word = random.sample(Dictionary.items(), 1)[0]
    print("Hint: " + hint)      
    print("_" * len(chosen_word))
    return chosen_word

choose_word()

印刷:

Hint: mammal
__

回報:

Out[2]: ['horse', 'giraffe']

根據random.sample的文檔,它將返回從總體序列或集合中選擇的唯一元素列表。

在您的示例代碼中, random.sample(Dictionary.items(), 2)將返回一個長度為 2 的列表。

In [1]: random.sample(Dictionary.items(), 2)                                                                                                                                                  
Out[1]: [('occupation', ['fireman', 'doctor']), ('mammal', ['horse', 'giraffe'])]

您需要將random.sample方法的參數從 2 更改為 1 並在擴展時,

hint, chosen_word = random.sample(Dictionary.items(), 1)[0]

hint包含鍵,並且chosen_word將包含值列表。

參考@Yogaraj 和@mcsoini 后我找到了解決方案

import random


Dictionary = {"fruits": ["watermelon", "papaya", "apple"],
              "buildings": ["apartment", "museum"],
              "mammal": ["horse", "giraffe"],
              "occupation": ["fireman", "doctor"]}


def choose_word():
    hint, chosen_words = random.choice(list(Dictionary.items()))
    print("Hint: " + hint)
    chosen_word = random.choice(list(chosen_words))
    print("_" * len(chosen_word))
    return chosen_word

它有點長,但它設法避免使用 random.sample() 因為它無論如何都被棄用了。

暫無
暫無

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

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