简体   繁体   English

用for循环填充列表

[英]Filling out a list with for loop

I want to make a simple slot machine. 我想做一个简单的老虎机。 The machine should be 5*3 slots big. 机器应该是5 * 3插槽大。 There are two items: 0 and 1. 0 means nothing and 1 is a win. 有两个项目:0和1。0表示无意义,1表示获胜。 My code so far: 到目前为止,我的代码:

import random

# slot machine
# [][][][][]
# [][][][][]
# [][][][][]

machine = [
    (), (), (), (), (),
    (), (), (), (), (),
    (), (), (), (), ()
]

for slot in machine:
    random.randrange(2)

So in the for loop are generated 15 numbers (0 or 1) and they should go in the slots (tuples). 因此,在for循环中生成了15个数字(0或1),它们应该放入插槽(元组)中。

Just use list comprehension: 只需使用列表理解:

machine = [random.choice([0, 1]) for i in range(15)]

Sample output: 样本输出:

>>> print(machine)
>>> [0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0]

If you want a "matrix" instead, you can do the following: 如果要使用“矩阵”,则可以执行以下操作:

machine = [[random.choice([0, 1]) for i in range(5)] for j in range(3)]

Sample output: 样本输出:

>>> for row in matrix:
...     print(row)
[0, 0, 0, 1, 0]
[1, 1, 1, 0, 1]
[1, 0, 0, 1, 1]
>>>
import random

machine = []
for x in range(3):
    machine.append([random.randrange(2) for i in range(5)])
print(machine)

Sample output: 样本输出:

[[0, 0, 0, 1, 1], [0, 0, 1, 0, 0], [0, 1, 1, 0, 0]]

A one liner solution, but harder to read to some people could be: 一个单一的解决方案,但对于某些人来说更难理解:

import random
print([[random.randrange(2) for i in range(5)] for x in range(3)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM