如何在python中创建列表列表

时间:2013-03-05 03:15:56

标签: 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))

我知道为什么这会让我知道它做了什么,只是不知道该怎么做。请给出最简单的答案,新的,但还不知道。

2 个答案:

答案 0 :(得分:1)

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

注意每次在第一个for循环中我是如何创建一个空数组(list500steps)的?然后,在创建所有步骤之后,我将该数组(现在不是空的)附加到散步数组中。

答案 1 :(得分: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 

您可能希望打印其中一个列表以检查输入。