1

所以我刚开始学习python,每周都会从朋友那里得到迷你课程。这周要做一个简单的老虎机游戏。老虎机中有 6 个项目,当出现 3 个或更多相同项目时,用户获胜。我试过下面的代码:

for i in slotScreen:
    if slotScreen.count(i) == 3:
        print('You got 3 of the same! You win!')

当列表中的第一项是同类 3 的一部分时,该代码有效,但如果三个元素都不是列表中的第一个,则该代码不起作用,如下所示:

slotScreen = ['lemon', 'cherry', 'lemon', 'lemon', 'pirate', 'bar']  # works

slotScreen = ['cherry', 'lemon', 'lemon', 'lemon', 'pirate', 'bar']  # not work

知道为什么会这样吗?

编辑:更多代码。当我应该收到 You win 3x 消息时,我收到了 You Lose 消息。

        for i in slotScreen:
            if slotScreen.count(i) == 6:
                print('You win 10x your bet!!!')
                x = x + int(bet) * 10
                break

            elif slotScreen.count(i) == 5:
                print('You win 5x your bet!')
                x = x + int(bet) * 5
                break

            elif slotScreen.count(i) == 4:
                print('You win 4x your bet!')
                x = x + int(bet) * 4
                break

            elif slotScreen.count(i) == 3:
                print('You win 3x your bet!')
                x = x + int(bet) * 3
                break

            elif slotScreen.count(i) <= 2:
                print('Sorry you lose')
                break
4

6 回答 6

4

您的程序总是break在第一次for迭代中执行,因此它只计算列表的第一个元素。

于 2012-07-21T07:10:52.220 回答
3

Marco de Wit's response is correct. I thought I would offer a possible solution.

from collections import Counter

counter = Counter(['cherry', 'lemon', 'lemon', 'lemon', 'pirate', 'bar'])
symbol, count = counter.most_common(1)[0]

This will give you the symbol (in this case, 'lemon') and its count (in this case, 3) of the most common symbol in the list (if you want to deal with ties, you'll need to extend this).

于 2012-07-21T07:29:04.277 回答
1

你的代码对我有用:http: //ideone.com/CKNZb

于 2012-07-21T06:17:41.660 回答
0

您可以尝试转换为 a set,然后比较:

def main():
    a = [1, 1]
    b = [1, 2]
    print(contains_multiple(a))  # `True`
    print(contains_multiple(b))  # `False`


def contains_multiple(x):
    """Return `True` if `x` contains multiplicates."""
    return len(x) != len(set(x))


if __name__ == '__main__':
    main()

为了避免在 alist包含一些不可散列的项目时出现错误,请使用:

from collections.abc import Hashable


def contains_multiple(x):
    """Return `True` if `x` contains multiplicates."""
    return len(x) != len(unique(x))


def unique(iterable):
    """Return `list` of unique items in `iterable`."""
    if all(is_hashable(x) for x in iterable):
        return set(list(iterable))
    unique = list()
    for item in iterable:
        if item in iterable:
            continue
        unique.append(item)
    return unique


def is_hashable(x):
    """Return `True` if `x` is hashable."""
    return isinstance(x, Hashable)
于 2013-07-13T02:11:59.640 回答
0

使用 dict 理解来制作直方图,然后检查它。

>>> L = ['cherry', 'lemon', 'lemon', 'bar', 'bar', 'bar']
>>> d = {f: L.count(f) for f in set(L)}
>>> for fruit in d:
        if d[fruit] > 2:
            print("You got {} {}'s! You win!").format(d[fruit], fruit)

You got 3 bar's! You win!

这段代码现在可能看起来很神秘,但一旦你学会阅读和理解列表和字典推导式,它们就会更容易使用并且更不容易出错。

这是创建然后命名为 d 的字典。它将每个水果作为键,并计算值:

>>> {f: L.count(f) for f in set(L)}
{'cherry': 1, 'lemon': 2, 'bar': 3}

python 中的 for 循环可用于循环遍历字典的键,就像列表中的项目或任何其他可迭代项一样容易。然后,您可以使用每个键来访问计数值并对其进行测试。

于 2013-07-13T02:40:39.427 回答
0

虽然我认为其他一些答案已经给出了替代实现,但我认为看看如何修复您当前的算法可能会很有用:

    for i in slotScreen:
        if slotScreen.count(i) == 6:
            print('You win 10x your bet!!!')
            x = x + int(bet) * 10
            break

        elif slotScreen.count(i) == 5:
            print('You win 5x your bet!')
            x = x + int(bet) * 5
            break

        elif slotScreen.count(i) == 4:
            print('You win 4x your bet!')
            x = x + int(bet) * 4
            break

        elif slotScreen.count(i) == 3:
            print('You win 3x your bet!')
            x = x + int(bet) * 3
            break

        # no else clause on the if statement, because we can't tell if you've lost yet

    else:  # this else block is attached to the for, and runs if no break was hit
        print('Sorry you lose')

else这使用了可以放在for循环之后的有点晦涩的子句。else仅当循环运行完成时才会运行该块,而不是通过break语句提前退出。这意味着只有在检查了列表中的所有值之后才会出现“你输了”代码。请注意,您实际上可以提前停止,因为如果您检查了六长列表中的前 4 个值,则在最后两个值中找不到任何三种值。

您还可以进行一些其他小的改进,例如slotScreen.count(i)每个循环只运行一次循环并将其保存到可以由每个if/elif测试测试的变量中。

于 2013-07-13T02:49:08.673 回答