【问题标题】:Random dictionary searches which never returns same item twice永远不会返回相同项目两次的随机字典搜索
【发布时间】: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


【解决方案1】:

您可以从字典中获取键,从该列表中选择随机元素,获取字典条目并随后从列表中删除键。

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)

【讨论】:

  • @Redunited 上面的评论不在此处。只需编辑您的问题并粘贴代码。如果您弄错了,有人会为您编辑它,但代码应该在三个 ``` 块中(esc 下面的键)
【解决方案2】:

使用集合来收集您想要的密钥。 向要求定义的函数提供 set 和 dict,以便它可以向其添加新键 - 不要使用全局变量。 循环直到无法再猜测 (len(already)==len(data)) 并处理这种情况,或者直到用户想要退出:

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.')

【讨论】:

    猜你喜欢
    • 2012-10-22
    • 2019-10-09
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 2013-03-12
    • 1970-01-01
    相关资源
    最近更新 更多