简体   繁体   English

如何在python中创建列表列表

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

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

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? 请注意,我是如何在第一个for循环中每次创建一个空数组(list500steps)的? 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. 您可能需要打印列表之一来检查输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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