如何在 Python 中创建相反的字符串?

How to create the opposite string in Python?

我是 Python 的新手,我正在尝试 运行 使用最基本的轮盘赌策略进行一些测试。因此,我的策略的主要思想是:您押注随机颜色(红色或黑色)。以红色为例。如果轮盘赌的结果也是红色,您将赌注改为黑色。但是,如果小球击中了相反的颜色,在我们的例子中是黑色,您不会改变颜色,而是将赌注加倍并继续,直到您的颜色出现在轮盘上。 所以我设法创建了一个轮盘模拟,但是当我的颜色出现在轮盘上并且我需要更改相反的颜色时,我对这部分有点挣扎。

import random

start_money = 100
coef = 0.001
win = 0
loss = 0
money = start_money
colors = ["red", "red", "red", "red", "red", "red",
          "red", "red", "red", "red", "red", "red",
          "red", "red", "red", "red", "red", "red",
          "black", "black", "black", "black", "black", "black",
          "black", "black", "black", "black", "black", "black",
          "black", "black", "black", "black", "black", "black", "zero"]

while money > 0:
    bet = start_money * coef
    if bet > money:
        bet = money
    money -= bet
    bet_color = random.choice(["red", "black"])
    result = random.choice(colors)
    if result == bet_color:
        money += bet * 2
        win += 1
    else:
        loss += 1
games = win + loss

这是现在的样子。但是如果我的赌注赢了而没有为我可能得到的每个可能结果写下条件,我真的不知道如何改变颜色。

定义一个returns相反颜色的函数:

def other_color(color):
    if color == 'red':
        return 'black'
    else:
        return 'red'

然后当你想改变颜色时,你可以使用

bet_color = other_color(bet_color)

或者您可以使用条件运算符将其作为单行代码执行:

bet_color = 'red' if bet_color == 'black' else 'black'