2016-04-21 67 views
2
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。一些指向正確方向的指針會很好。使用隨機數在Python中創建二維列表。

+0

你可能需要重新row'''到[]'你追加到'first_gen' – Julien

+0

你們是不是要'後一個reshape' 1D列表爲2D名單?病毒列表有7個數字,而3x3列表則有12個數字。 – roadrunner66

+0

row = []肯定應該在第一個for循環中。 – roadrunner66

回答

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]] 
+0

謝謝!正是我需要的 –

0

你分配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) 

不過,我更喜歡使用列表理解這些各種各樣的事情。這裏是一個另類:

from pprint import pprint 
import random 

rows = 3 
cols = 3 
virus = [0,0,0,0,0,1,2] 

first_gen = [[random.choice(virus) for _ in range(rows)] for _ in range(cols)] 
pprint (first_gen) 
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]]