簡體   English   中英

如何在python中創建列表列表

[英]How to make a list of lists in python

我試圖使用random.random()在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))

我知道為什么這會讓我做什么,只是不知道該怎么做。 請給出一個最簡單的答案,現在還不太了解。

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

請注意,我是如何在第一個for循環中每次創建一個空數組(list500steps)的? 然后,在創建所有步驟之后,我將該數組(現在不為空)追加到行走數組。

 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 

您可能需要打印列表之一來檢查輸入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM