从Python中的字典中提取彼此不相等的随机密钥

kid*_*eme 6 python dictionary function python-2.7

所以我试图通过Python设置多项选择测验.我对Python很陌生,所以如果有更简单的方法可以预先表示道歉.但是,在尝试更新的技术之前,我正试图真正理解一些基础知识.

我有一本字典.在这本字典中,我想要抓住3个随机密钥.我还想确保这三个键不相等(换句话说,彼此随机).这是我到目前为止写的代码:

import random

word_drills = {'class': 'Tell Python to make a new kind of thing.',
               'object': 'Two meanings: the most basic kind of thing, and any instance of some thing.',
               'instance': 'What you get when you tell Python to create a class.',
               'def': 'How you define a function inside a class.',
               'self': 'Inside the functions in a class, self is a variable for the instance/object being accessed.',
               'inheritance': 'The concept that one class can inherit traits from another class, much like you and your parents.',
               'composition': 'The concept that a class can be composed of other classes as parts, much like how a car has wheels.',
               'attribute': 'A property classes have that are from composition and are usually variables.',
               'is-a': 'A phrase to say that something inherits from another, as in a Salmon *** Fish',
               'has-a': 'A phrase to say that something is composed of other things or has a trait, as in a Salmon *** mouth.'}

key1 = ' '
key2 = ' '
key3 = ' '             

def nodupchoice():
    while key1 == key2 == key3: 
        key1 = random.choice(word_drills.keys())
        key2 = random.choice(word_drills.keys())
        key3 = random.choice(word_drills.keys())


nodupchoice()

print "Key #1: %s, Key #2: %s, Key #3: %s" % (key1, key2, key3)
Run Code Online (Sandbox Code Playgroud)

我很确定问题在于我的while循环.我想创建一个将继续运行的功能,直到所有三个键彼此不同.最后,它会打印结果.有任何想法吗?提前致谢.

DSM*_*DSM 12

你可以使用random.sample:

>>> random.sample(word_drills, 3)
['has-a', 'attribute', 'instance']
Run Code Online (Sandbox Code Playgroud)

并且您不需要.keys(),通过字典迭代是在键上.

请注意,random.sample将从您提供的列表中返回三个唯一值(即它将永远不会返回'has-a'两次):

>>> all(len(set(random.sample(word_drills, 3))) == 3 for i in range(10**5))
True
Run Code Online (Sandbox Code Playgroud)

  • 我建议你使用键本身列表,只需使用`keys = random.sample(word_drills,3)`,然后通过`keys [0]`和`keys [1]`和`keys [来访问它们]. 2]`.90%的时间在变量名中使用数字后缀时,这表明您确实需要列表或元组或字典.但是如果你想要三个单独的名字,你可以简单地写`key1,key2,key3 = random.sample(word_drills,3)`. (2认同)