简体   繁体   中英

How to make a list of lists in python

I am trying to make a list of lists in python using random.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())

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))

I know why this gives me what it does, just don't know how to do something about it. Please give the simplest answer, in new at this and don't know a lot yet.

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

Notice how I am creating an empty array (list500steps) each time in the first for loop? Then, after creating all the steps I append that array (Which is now NOT empty) to the array of walks.

 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 

You might want to print one of the lists to check the input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM