6

所以我正在尝试通过 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)

我很确定问题出在我的 while 循环上。我想创建一个函数,它会一直运行直到所有三个键都不同。最后,它将打印结果。有任何想法吗?提前致谢。

4

6 回答 6

12

您可以使用random.sample

>>> random.sample(word_drills, 3)
['has-a', 'attribute', 'instance']

而且你不需要.keys(),对字典的迭代是对键的。

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

>>> all(len(set(random.sample(word_drills, 3))) == 3 for i in range(10**5))
True
于 2012-08-18T21:05:34.303 回答
3

采用random.sample

>>> import random
>>> random.sample([1,2,3,4,5,6], 3)
[4, 5, 2]
于 2012-08-18T21:04:50.803 回答
0

可能最简单的事情是shuffle按键:

keysShuffled = list(word_drills)
random.shuffle(keysShuffled)

然后取前3个

threeUnique = keysShuffled[:3]
于 2012-08-18T21:05:46.603 回答
0

也许你想试试Quiz Me 2.5?它是 Python 3.x 中带有 GUI 的多项选择测验系统。

于 2012-08-18T21:21:36.457 回答
0

正如其他人所解释的那样,random.sample这是做你想做的最好的方式。

解释为什么您的原始代码不起作用:

第一个问题,您的while循环存在逻辑错误 - 只要两个项目不同,它就会结束(例如'a' == 'a' == 'b',为真,循环将结束),要解决这个问题,有几种方法:

while not (key1 != key2 != key3):

或者,aset只能包含唯一项,因此当长度set([key1, key2, key3])为 3 时,所有三个值都不同:

while len(set([key1, key2, key3]) != 3:

第二个问题,以及代码将拒绝运行的原因:

key1 key2 key3被定义为全局变量(key1 = ' ' are at the top-level of your.py` 文件,不在函数中)

您可以毫无问题地在函数中查找全局变量(就像您在哪里完成的那样while key1 == key2 ...)。发生错误是因为您还尝试在循环中分配to key1- 这会使 Python 的解析器感到困惑,因为您正在查找while key1 == ...部件中的全局变量,但尝试在下一行创建一个新的函数局部变量,因此它会抛出一个错误。

解决此问题的垃圾方法如下:

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

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

然后它将按您的预期工作,但不要那样做 - 全局变量有它们的用途,但这不是这种情况..

您可以轻松地从函数返回多个值,而不是使用全局变量:

def nodupchoice():
    key1 = ' ' # local variables, which are inaccessible outside this function
    key2 = ' '
    key3 = ' '

    while not (key1 != key2 != key3):
        key1 = random.choice(word_drills.keys())
        key2 = random.choice(word_drills.keys())
        key3 = random.choice(word_drills.keys())

    return key1, key2, key3


key1, key2, key3 = nodupchoice()

print "Key #1: %s, Key #2: %s, Key #3: %s" % (key1, key2, key3)

哦,甚至更好的是,您可以传入word_drills作为参数:

def nodupchoice(things):
    key1 = ' ' # local variables, which are inaccessible outside this function
    key2 = ' '
    key3 = ' '

    while not (key1 != key2 != key3):
        key1 = random.choice(things)
        key2 = random.choice(things)
        key3 = random.choice(things)

    return key1, key2, key3


key1, key2, key3 = nodupchoice(word_drills)

...并且您编写的函数几乎与random.sample(word_drills, 3)!

于 2012-08-18T21:35:03.733 回答
-1

我遇到了同样的问题并写了https://github.com/robtandy/randomdict来解决它。也许它也会帮助你。

它提供了一个 python dict 对象,但带有附加方法,random_key、random_value 和 random_item。所有这些都具有 O(1) 的运行时间复杂度。

于 2015-09-27T15:13:03.573 回答