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