Python随机开胃菜

2024-10-16 20:52:29 发布

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

我正在尝试创建一个函数,在这个函数中,我给它一个列表,列出我预计的比赛结果和我的赌注。例如,我可以预测结果[1,3,4,2],其中马1在第一,马3,第二等等。。。如果我把这两个词都列出来比较一下,如果我没有把这两个词都放在一起比较的话。我卡住了!!!在

def horseRace(gList,bet):

    import random

    a = [1,2,3,4]
    random.shuffle(a,random.random)
    i = 0
    x = 0
    while i < len(gList):
        if gList[i] == a[0]:
            x = x + 1
        if gList[i] == a[1]:
            x = x + 1
        if gList[i] == a[2]:
            x = x + 1
        if gList[i] == a[3]:
            x = x + 1
        else:
            x = x
        i = i + 1
    print(x)
    print(a)
    print(gList)
    if x == 4:
        money = bet*2
        print("You guessed 4 position(s) correctly and won $ %d !"%money)
    if x == 0:
        money = 0.00
        print("You guessed no position(s) correctly and won $ %d !"%money)
    if x == 1:
        money = bet
        print("You guessed 1 position(s) correctly and won $ %d !"%money)

    if x == 2:
        money = bet
        print("You guessed 2 position(s) correctly and won $ %d !"%money)

    if x == 3:
        money = bet
        print("You guessed 3 position(s) correctly and won $ %d !"%money)

Tags: and函数you列表ifpositionrandomprint
3条回答

你的while循环应该更像这样

  while i < len(gList):
        if gList[i] == a[i]:
            x = x + 1
        else:
            x = x
        i = i + 1

这样,就可以比较gList中单元格位置i的值与a中相同单元格位置的值。现在,您的代码实际上是说只要值gList[i]等于以下任一值,就向x添加一个:

a[1]a[2]a[3]a[4]

当然是哪个

你可以用更像Python的方式来做,在一行中计算出正确的猜测数:

nCorrect = len(filter(lambda x: x[0]==x[1], zip(randomized,gList)))

下面是完整的代码,我将在下面解释:

^{pr2}$

您应该根据计算结果的方式更改getResult方法。在

我来解释这句话:

nCorrect = len(filter(lambda x: x[0]==x[1], zip(randomized,gList)))

因此,首先,它将把randomized和{}组合成一个元组列表:

gList = [1,2,3,4]
randomized = [1,3,2,4]
print zip(randomized,gList)
    [(1,1), (2,3), (3,2), (4,4)]

那么filter将只接受与条件匹配的元素。在本例中,条件是元组的第一个元素等于元组的第二个元素(x[0]==x[1]

print filter(lambda x: x[0]==x[1], zip(randomized,gList))
[(1,1), (4,4)]

然后我们返回数组的长度,即正确猜测的次数。在

考虑使用for循环来计算正确猜测的次数。假设gList和{}大小相同:

for (gList_i, a_i) in zip(gList, a):
    if g_List_i == a_i:
        x += 1

另外,可能是消息的函数,它将正确猜测的位置数作为输入。在

^{pr2}$

相关问题 更多 >