python - 将 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
解决方案
实现这一点的更简单方法是使用列表推导:
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
...
推荐阅读
- reactjs - CSSTransition(react-transition-group),React Portal Modal 没有动画
- c++ - OpenGL:顶点缓冲区如何管理其内存?
- javascript - 反应:尝试一致地读取自定义文件会导致 index.html
- mysql - 在moodle sql报告中添加论坛参与
- mongodb - MongoDB 不会保存 url 字符串
- c - 如何使用 Scitools 理解的 C API 在 * .cpp 文件中查找特定的词位?
- mongodb - Lambda 到 Mongodb EC2 实例连接问题
- flutter - Flutter 插件——去除某些依赖
- python - 芹菜不启动任务python django
- crash - 在打开浏览器进行调试时颤动网络崩溃