Python错误随机.choi

2024-04-19 23:33:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个小程序(测试)来测试这种语言,但我被困在一个函数中 让我解释一下 我希望从我的数据库中接收值,然后只使用其中的5个值,因此对于每个问题,用户都会回答,然后转到下一个问题,直到到达最后一个问题为止。 到目前为止我掌握的代码是

def escolhaFinal(id_tema, id_tipo):
    cur = conn.cursor()
    cur.execute("SELECT question,op1,op2,op3,op4,correto FROM questions where id_tema = %s and id_grau = %s", (id_tema,id_tipo))
    data = cur.fetchall()
    l = list(data)
    random.choice(l,5)
    for row in l:
            print(l)


    cur.close()
    conn.close()

但我收到了这个错误 TypeError:choice()接受2个位置参数,但给出了3个

关于这个功能有什么帮助吗?在


Tags: 函数代码用户程序语言id数据库close
3条回答

在随机选择只接受1个参数。在你的代码里

 random.choice(l,5)

那5个人该怎么办?文档中有这样的选择:“从非空序列seq返回一个随机元素。如果seq为空,则引发索引器错误。“

因此,将行更改为只使用1个参数,并指定值以便以后使用(也可以调整代码的其余部分)。在

看起来您希望使用random.sample,因为这样可以从列表中返回多个随机选择的项目,例如:

>>> import random
>>> myList = range(100)
>>> winners = random.sample(myList, 5)
>>> print winners
[79, 10, 32, 98, 82]
>>>

^{}的文档中可以看到:

random.choice(seq)

Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.

要选择多个元素,可以使用list comprehension,如下所示:

[random.choice(l) for i in range(5)]

^{}选择唯一元素:

^{pr2}$

输出:

>>> import random
>>>
>>> l = [1, 2, 3, 4, 5]
>>> random.sample(l, 3)  # unique elements
[4, 2, 5]
>>>
>>> [random.choice(l) for i in range(3)]  # Note that we have 3 twice!
[3, 5, 3]

相关问题 更多 >