Python 从不两次返回同一项的随机字典搜索
当要求程序从键值条目字典中选择一个随机条目时,是否有一种方法,一旦每个条目都被选中,程序会让用户知道所有条目都被选中,然后停止,最终只允许每个条目被选中一次,如果只有3个条目,程序将只运行3次,如果有100个条目,程序将运行100次,依此类推?python编码新手,请耐心听我说Python 从不两次返回同一项的随机字典搜索,python,python-3.x,loops,dictionary,search,Python,Python 3.x,Loops,Dictionary,Search,当要求程序从键值条目字典中选择一个随机条目时,是否有一种方法,一旦每个条目都被选中,程序会让用户知道所有条目都被选中,然后停止,最终只允许每个条目被选中一次,如果只有3个条目,程序将只运行3次,如果有100个条目,程序将运行100次,依此类推?python编码新手,请耐心听我说 from random import * def show_keys(): """ Show the user a random key and ask them to define it. Sh
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.')
您可以从字典中获取键,从该列表中选择随机元素,获取字典条目,然后从列表中删除键
import random
dictionary = {
'one': '1',
'two': '2',
'three': '3'
}
# getting list of keys from dictionary
keys = list(dictionary.keys())
print(keys)
# picking random elemt from list
elem = random.choice(keys)
print(elem, dictionary.get(elem))
# remove an element from a list
keys.remove(elem)
print(keys)
使用集合收集您需要的钥匙。 向要求定义的函数提供集合和dict,以便它可以向其中添加新键-不要使用全局变量。 循环直到不再可能猜测(
len(已经)==len(数据)
)并处理该情况,或者直到用户想要退出:
from random import choice # do not import ALL - just what you need
def show_keys(d,a): # provide data and already used key set
""" Show the user a random key and ask them
to define it. Show the definition
when the user presses return.
d : your dict of keys and definitions
a : a set of already used keys
"""
# choice only for those keys that are not yet used
random_key = choice( [k for k in d if k not in a] )
print('Define: ', random_key)
input('Press return to see the definition')
print(d [random_key])
# add used key to a - you could ask (y/n) if the definition was correct
# and only then add the key - if wrong it has a chance of being asked again
a.add(random_key)
# Set up the data with keys and defs
data = {'key1':'definition1',
'key2':'definition2',
'key3':'definition3'}
# set up already seen keys
already = set()
# The loop
while True: # loop until break
# nothing more to guess
if len(already)==len(data):
y = input("Game over. Play again? [y, ]").lower()
if y=="y":
# reset set of seen stuff to empty set()
already = set()
else:
break
user_input = input('Enter s to show a key, or q to quit: ')
if user_input == 'q':
break
elif user_input == 's':
# provide data and already to the function, don't use globals
show_keys(data,already)
else:
print('You need to enter either q or s.')
或者:创建一个无序列表并使用:
from random import shuffle
data = {'key1':'definition1',
'key2':'definition2',
'key3':'definition3'}
already = set()
shuffled = list(data.items())
shuffle(shuffled)
# The loop
while shuffled:
user_input = input('Enter s to show a key, or q to quit: ')
if user_input == 'q':
break
elif user_input == 's':
key,value = shuffled.pop()
print('Define: ', key)
input('Press return to see the definition')
print(value)
else:
print('You need to enter either q or s.')
将所有键放入一个列表,random.shuffle()列表中,弹出最后一个键,直到其为空。您可以获取所有键,将它们放入一个列表中,对列表进行洗牌,然后按顺序从列表中选择它们。您应该在问题中添加一些代码。人们更有可能以这种方式做出反应。@PatrickArtner做
随机选择会更有效。选择(…)
@Err取决于具体情况。假设您想用3到1000个键“清空”dict:将所有键的列表洗牌一次,然后从列表中弹出,直到清空,这样成本更低,然后执行choice()1000次和list.remove()1000次。如果您可以从dict本身删除密钥,那么使用dict中的选择并在之后删除密钥会更好,因为不需要列表-列表的提示是:dict未更改,您可以通过重新填充dict来“重新运行”游戏list@Redunited上面的评论不在这里。只需编辑您的问题并粘贴代码。如果你弄错了,有人会帮你编辑,但是代码应该在三个``块中(下面的键是esc
)