使用随机数在python中创建二维列表。

时间:2016-04-21 02:05:11

标签: python

import random

rows = 3
cols = 3 
virus = [0,0,0,0,0,1,2]
virus_level = random.choice(virus) 
first_gen = []
row =[]
for rownum in range(rows):
    for colnum in range(cols):
        virus_level = random.choice(virus)
        row.append(virus_level)
    first_gen.append(row)

我需要使用列表病毒中的随机数创建一个二维列表。这是我到目前为止,数字不是随机顺序,列表打印为9乘3,而不是3乘3.正确方向的一些指针会很好。

3 个答案:

答案 0 :(得分:0)

您对for (it = h.begin(); it != h.end(); ) { if (it->second > 4){ it = h.erase(it); // set it to iterator following the last removed element } else { ++it; } } 的作业应位于最外层循环中,如下所示:

row[]

但是,我更喜欢使用列表推导来处理这些事情。这是另一种选择:

import random

rows = 3
cols = 3
virus = [0,0,0,0,0,1,2]
virus_level = random.choice(virus)
first_gen = []
for rownum in range(rows):
    row = []
    for colnum in range(cols):
        virus_level = random.choice(virus)
        row.append(virus_level)
    first_gen.append(row)

答案 1 :(得分:0)

这就是诀窍:

>>> import random
>>> rows=3
>>> cols=3
>>> virus=[0,0,0,0,0,1,2]
>>> [[random.choice(virus) for r in range(rows)] for c in range(cols)]
[[0, 2, 2], [0, 0, 0], [0, 0, 0]]

答案 2 :(得分:0)

您需要在每个循环中重置row

按原样使用您的代码段,如果您只是将row =[]行放在外部循环中,那么应该会给您正确的结果。

import random

rows = 3
cols = 3 
virus = [0,0,0,0,0,1,2]
virus_level = random.choice(virus) 
first_gen = []
for rownum in range(rows):
    row = []    
    for colnum in range(cols):
        virus_level = random.choice(virus)
        row.append(virus_level)
    first_gen.append(row)

print first_gen  # [[2, 0, 0], [0, 0, 0], [1, 0, 0]]