首页 > 解决方案 > 将 FOR LOOP 的所有结果存储在数组中

问题描述

我创建了一个名为 Player1_Cards 的数组。每张卡片都需要有一个数字和颜色。Player1 应该有 15 张牌,可以从 1 到 30 编号。

我使用了一个 for 循环来做到这一点:

使用 random.randint (1,30),我找到了卡号。

使用 random.randint(1,3),我将数字 1,2 或 3 分配给红色、黄色或黑色。

如何将 for 循环中的所有结果存储为数组?

这是我的代码:

Player1_Cards = [0]

import random
for i in range(1,16):
    i = random.randint(1,30)
    i_colour = random.randint(1,3)
    i_colour = str(i_colour)

    if i_colour == "1":
        i_colour = "RED"

    if i_colour == "2":
        i_colour = "YELLOW"

    if i_colour == "3":
        i_colour = "BLACK"



    Player1_Cards[i,i_colour]

如果我打印(i,i_colour),忽略数组,它可能执行的示例是:

6 YELLOW
28 YELLOW
8 RED
3 BLACK
22 RED
2 BLACK
26 RED
25 YELLOW
8 RED
20 RED
16 BLACK
12 YELLOW
4 RED
20 BLACK
1 YELLOW

标签: pythonfunctionloopsfor-looprandom

解决方案


实现这一点的更简单方法是使用列表推导:

import random

colours = ['RED', 'BLUE', 'YEllOW']
player_hand = [(random.randint(1, 30), random.choice(colours)) for _ in range(15)]

Output:
# 21 BLUE
# 22 BLUE
# 25 YEllOW
# 11 BLUE
# 4 RED
...

推荐阅读