存储数组中FOR LOOP的所有结果

问题描述 投票:0回答:2

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

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

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

使用random.randint(1,3),我将数字1,2或3分配给颜色RED,YELLOW或BLACK。

如何将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
python function loops for-loop random
2个回答
1
投票

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

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
...

0
投票

试试这个:

Player1_Cards = []

在一开始的时候。然后在循环结束时:

Player1_Cards.append((i, i_colour))

循环之后:

print(Player1_Cards)

你的代码中也有一个错误:

for i in range(1,16):
    i = random.randint(1,30)

两者都将变量i设置为一个值。这种方式没有意义。如果你只想做你的循环十五次,最好使用_代替:

for _ in range(1,16):
© www.soinside.com 2019 - 2024. All rights reserved.