python - 抽认卡抛硬币词典

标签 python python-3.x dictionary random choice

有点受困于这段代码。 我正在尝试从字典中以随机顺序打印键或值。 (随机是先显示词条还是先显示对应的定义) 但我只得到一个键,然后是一个值。 我缺少什么代码才能工作? 任何帮助都会很棒。谢谢你 示例:

  • Test-1(按回车键)Definition-1
  • 定义-4(按回车键)测试-4
  • 定义-2(按回车键)测试-2
  • Test-3(按回车键)Definition-3 ...

来自随机导入*

def flashcard():
    random_key = choice(list(dictionary))
    print('Define: ', random_key)
    input('Press return to see the definition')
    print(dictionary[random_key])

dictionary = {'Test-1':'Definition-1',
            'Test-2':'Definition-2',
            'Test-3':'Definition-3',
            'Test-4':'Definition-4'}

exit = False while not exit:
    user_input = input('Enter s to show a flashcard and q to quit: ')
    if user_input == 'q':
        exit = True
    elif user_input == 's':
        flashcard()
    else:
        print('You need to enter either q or s.')

最佳答案

您可以在 0 和 1 之间选择一个随机整数,也可以在 0 和 1 之间选择。

def flashcard():
    k, v = choice(list(dictionary.items()))
    # toss a coin to decide whether to show the key or the value
    # alternative is randint(0, 1)
    if choice((True, False)):
        print('Define: ', k)
        input('Press return to see the definition')
        print(v)
    else:
        print('What is: ', v)
        input('Press return to see the key')
        print(k)

关于python - 抽认卡抛硬币词典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73281555/

相关文章:

python - 加速 n-gram 处理

python - 错误: command 'cc' failed with exit status 1 on Mac for pip install MySQL-python

python - 在从 __init__ 调用的函数中声明变量是否仍然使用 key 共享字典?

c# - 使用 linq 合并 2 个具有重复键的字典

Python 无法正确排序 Unicode

python-3.x - Openpyxl创建带有表格的excel文件导致需要恢复错误的文件

python - 我无法使用 re.split 来处理数字,但将它们保留在字符串中并放在一起,

具有重复键但值不同的python3字典

python - 如何使用 Python 按字母数字顺序按值对字典进行排序?

python - 打开 : differences between python 2 and 3