关于python:如何压缩if语句

How to condense if statments

本问题已经有最佳答案,请猛点这里访问。

我正在用Python制作一个可以玩战争游戏的程序。我想知道是否有一种方法可以将所有的if语句压缩成一个更简单的代码。我需要从1-13中选择一个随机数,这些数字与牌组中的一张牌有关。1=ACE,2=2…11=杰克,12=女王,13=国王。我还没有学过任何函数,所以我不能使用它们中的任何一个。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    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
2
3
cards = ["Ace","Two","Three", ...,"King"]
card_picked_player = cards[player_picked-1]
card_picked_computer = cards[computer_picked-1]

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

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