有点被这个密码困住了。我正试着从字典中随机地打印键或值。(是先显示条目还是显示相应的定义),但我只得到一个键,后面跟着一个值。我错过了什么代码才能起作用?任何帮助都会是惊人的。谢谢你的例子:
随机进口*
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.')发布于 2022-08-08 17:11:24
您可以在0到1之间选择一个随机的int,也可以在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)发布于 2022-08-08 17:10:12
使用random.random确定是否应首先显示random_key或定义
from random import *
def flashcard():
random_key = choice(list(dictionary))
if random() > 0.5:
print("Define: ", random_key)
input("Press return to see the definition")
print(dictionary[random_key])
else:
print("Define: ", dictionary[random_key])
input("Press return to see the key")
print(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.")发布于 2022-08-09 09:57:26
另一个选项是使用sample (学习更多):
from random import choice,sample
def flashcard():
print('Define: {}\nThe key: {}'.format(*sample(choice([*dictionary.items()]),2)))
dictionary = {'Test-1':'Definition-1',
'Test-2':'Definition-2',
'Test-3':'Definition-3',
'Test-4':'Definition-4'}
# testing
for _ in range(3):
flashcard()
print()
>>> out
'''
Define: Test-4
The key: Definition-4
Define: Definition-1
The key: Test-1
Define: Definition-2
The key: Test-2https://stackoverflow.com/questions/73281555
复制相似问题