如何压缩如果声明

时间:2017-10-13 20:15:37

标签: python if-statement

我正在使用python制作一个可以玩战争游戏的程序。我想知道是否有办法将所有if语句压缩为更简单的代码。我需要从1-13中选择一个随机数,这些数字与牌组中的一张牌有关。 1 = Ace,2 = 2 ... 11 = Jack,12 = Queen,13 = King。我还没有学到任何功能,所以我不能使用其中的任何功能。

    while player_picked == computer_picked:
        player_picked = random.randint(1,13)
        computer_picked = random.randint(1,13)

        if player_picked == 1:
            card_picked_player = "Ace"
        if player_picked == 2:
            card_picked_player = "Two"
        if player_picked == 3:
            card_picked_player = "Three"
        if player_picked == 4:
            card_picked_player = "Four"
        if player_picked == 5:
            card_picked_player = "Five"
        if player_picked == 6:
            card_picked_player = "Six"
        if player_picked == 7:
            card_picked_player = "Seven"
        if player_picked == 8:
            card_picked_player = "Eight"
        if player_picked == 9:
            card_picked_player = "Nine"
        if player_picked == 10:
            card_picked_player = "Ten"
        if player_picked == 11:
            card_picked_player = "Jack"
        if player_picked == 12:
            card_picked_player = "Queen"
        if player_picked == 13:
            card_picked_player = "King"

        if computer_picked == 1:
            card_picked_computer = "Ace"
        if computer_picked == 2:
            card_picked_computer = "Two"
        if computer_picked == 3:
            card_picked_computer = "Three"
        if computer_picked == 4:
            card_picked_computer = "Four"
        if computer_picked == 5:
            card_picked_computer = "Five"
        if computer_picked == 6:
            card_picked_computer = "Six"
        if computer_picked == 7:
            card_picked_computer = "Seven"
        if computer_picked == 8:
            card_picked_computer = "Eight"
        if computer_picked == 9:
            card_picked_computer = "Nine"
        if computer_picked == 10:
            card_picked_computer = "Ten"
        if computer_picked == 11:
            card_picked_computer = "Jack"
        if computer_picked == 12:
            card_picked_computer = "Queen"
        if computer_picked == 13:
            card_picked_computer = "King"

1 个答案:

答案 0 :(得分:1)

使用列表,然后将列表编入索引。

cards = ["Ace", "Two", "Three", ..., "King"]
card_picked_player = cards[player_picked-1]
card_picked_computer = cards[computer_picked-1]

如果您不需要数值,也可以直接从列表中选择。

card_picked_player = random.choice(cards)
card_picked_computer = random.choice(cards)