2013-03-05 74 views
0

我正在嘗試使用random.random()在python中創建列表的列表。如何在python中創建列表的列表

def takeStep(prevPosition, maxStep): 

    """simulates taking a step between positive and negative maxStep, \ 
adds it to prevPosition and returns next position""" 

    nextPosition = prevPosition + (-maxStep + \ 
        (maxStep - (-maxStep)) * random.random()) 

list500Steps = [] 

list1000Walks = [] 

for kk in range(0,1000): 

    list1000Walks.append(list500Steps) 


    for jj in range(0 , 500): 

     list500Steps.append(list500Steps[-1] + takeStep(0 , MAX_STEP_SIZE)) 

我知道爲什麼這給了我它做什麼,只是不知道該怎麼做。請給出最簡單的答案,在這個新的,並不知道很多。

+0

另外:將參數「1000」硬編碼到變量名中通常是一個壞主意。 – DSM 2013-03-05 03:53:44

回答

1
for kk in xrange(0,1000): 
    list500steps = [] 
    for jj in range(0,500): 
     list500steps.append(...) 
    list1000walks.append(list500steps) 

注意我是如何創建一個空數組(list500steps)在第一個for循環,每次?然後,在創建所有步驟後,我將該數組(現在不是空的)附加到散步數組。

+0

這是有道理的。非常感謝! – user2134116 2013-03-05 03:32:29

+1

@ user2134116如果您喜歡IamAlexAlright的回答,那麼請務必將其標記爲已接受! – 2013-03-05 03:34:27

0
import random 

def takeStep(prevPosition, maxStep): 

    """simulates taking a step between positive and negative maxStep, \ 
     adds it to prevPosition and returns next position""" 

     nextPosition = prevPosition + (-maxStep + \ 
     (maxStep - (-maxStep)) * random.random()) 
     return nextPosition # You didn't have this, I'm not exactly sure what you were going for   #but I think this is it 
#Without this statement it will repeatedly crash 

list500Steps = [0] 
list1000Walks = [0] 
#The zeros are place holders so for the for loop (jj) below. That way 
#The first time it goes through the for loop it has something to index- 
#during "list500Steps.append(list500Steps[-1] <-- that will draw an eror without anything 
#in the loops. I don't know if that was your problem but it isn't good either way 



for kk in range(0,1000): 
    list1000Walks.append(list500Steps) 


for jj in range(0 , 500): 
    list500Steps.append(list500Steps[-1] + takeStep(0 , MAX_STEP_SIZE)) 
#I hope for MAX_STEP_SIZE you intend on (a) defining the variable (b) inputing in a number 

您可能想要打印其中一個列表以檢查輸入。

+0

這也是有道理的。我只是忘了粘貼在論壇上的功能返回。再次感謝您的幫助! – user2134116 2013-03-05 04:54:11