有点被这个代码束缚住了. 我正在try 以随机顺序打印词典中的键或值. (随机是先显示条目还是显示对应的定义) 但我只得到一个键,后跟一个值. 我遗漏了什么才能让代码正常工作? 任何帮助都会令人惊叹.谢谢 示例:

  • 测试-1(按回车键)定义-1
  • 定义-4(按回车键)测试-4
  • 定义-2(按回车键)测试-2
  • 测试-3(按Return键)定义-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之间 Select 一个随机整型,也可以在0和1之间进行 Select .

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相关问答推荐

运行终端命令时出现问题:pip start anonymous"

如何列举Pandigital Prime Set

Python虚拟环境的轻量级使用

PyQt5,如何使每个对象的 colored颜色 不同?'

所有列的滚动标准差,忽略NaN

使用NeuralProphet绘制置信区间时出错

连接一个rabrame和另一个1d rabrame不是问题,但当使用[...]'运算符会产生不同的结果

将JSON对象转换为Dataframe

旋转多边形而不改变内部空间关系

为什么Python内存中的列表大小与文档不匹配?

如何在验证文本列表时使正则表达式无序?

如何重新组织我的Pandas DataFrame,使列名成为列值?

按条件添加小计列

你能把函数的返回类型用作其他地方的类型吗?'

504未连接IB API TWS错误—即使API连接显示已接受''

ModuleNotFoundError:Python中没有名为google的模块''

我怎样才能让深度测试在OpenGL中使用Python和PyGame呢?

为什么在生成时间序列时,元组索引会超出范围?

解析CSV文件以将详细信息添加到XML文件

将鼠标悬停在海运`pairplot`的批注/高亮显示上