【发布时间】:2020-01-11 09:52:48
【问题描述】:
当要求程序从键值条目字典中选择一个随机条目时,有没有一种方法,一旦每个条目都被选中,一旦程序将让用户知道所有条目都已被选中,并且然后停止,最终只允许每个条目被选择一次,如果只有 3 个条目,程序将只运行 3 次,如果有 100 个条目,它将运行 100 次等等? python 编码新手,请多多包涵。
from random import *
def show_keys():
""" Show the user a random key and ask them
to define it. Show the definition
when the user presses return.
"""
random_key = choice(list(keys))
print('Define: ', random_key)
input('Press return to see the definition')
print(keys [random_key])
# Set up the keys
keys = {'key1':'definition1',
'key2':'definition2',
'key3':'definition3'}
# The loop
exit = False
while not exit:
user_input = input('Enter s to show a key, or q to quit: ')
if user_input == 'q':
exit = True
elif user_input == 's':
show_keys()
else:
print('You need to enter either q or s.')
【问题讨论】:
-
将所有键放入一个列表,random.shuffle() 列表,弹出最后一个直到为空。
-
你可以得到所有的键,把它们放在一个列表中,随机播放列表,然后从列表中按顺序选择它们
-
您应该在您的问题中添加一些代码。人们更有可能以这种方式回应。
-
@PatrickArtner 做
random.choice(...)会更有效率。 -
@Err 取决于。假设您想用 3 到 1000 个键“清空” dict:将所有键的列表 once 洗牌,然后从中弹出直到清空,然后执行 choice() 1000 次和 list.remove () 1000 次。如果您可以从字典本身中删除键,则使用字典中的选择并在之后删除键会更好,因为不需要列表 - 列表的优点是:字典不变,您可以通过重新填充列表来“重新运行”游戏跨度>
标签: python python-3.x loops dictionary search