1

I am trying to create a self populating matrix (Dictionary? Index? I don't know what it's called) with python code.

Here are two methods I tried


currentstair = [i for i in range(FLOOR - 2)]
for i in STAIRCASE:
    staircasenetwork.append([currentstair])

for j in range (STAIRCASE):
    for i in range (FLOOR - 2):
        staircasenetwork.append([j]i)

I want the list to start as [] and end as [[1,2,3],[1,2,3]]

mgilson
  • 300,191
  • 65
  • 633
  • 696

2 Answers2

0

You're on the right track. You're trying to make a list of lists. Probably the easiest way to understand how to do this is use a simple for loop that creates each of your sublists. You can use range to easily create the sublists:

>>> staircasenetwork = []
>>> for i in range(2):
...     staircasenetwork.append( range(1, 4) )
... 
>>> staircasenetwork
[[1, 2, 3], [1, 2, 3]]
mdml
  • 22,442
  • 8
  • 58
  • 66
0

I don't understand your question much since your question is kinda unclear about the variables and how many lists you want inside a list. But just try this out:

currentstair = []
for i in range(STAIRCASE):
    currentstair.append([])
    for j in range(FLOOR - 2):
        currentstair[-1].append(j+1)

So if you have:

STAIRCASE = 2
FLOOR = 5

Then the list out come will be [[1,2,3],[1,2,3]]

Brief explanation about my code: at first, the currentstair is assigned as an empty list []. Then, after the first loop, it will append another empty list inside the list corresponding to the STAIRCASE variable (which is 2 because you want to have 2 lists inside your own list). After that, the other for loop will append currentstair[-1] (the recently added list inside currentlist) a number j+1 since FLOOR - 2 equals to 5 - 2 = 3. So, the values of j+1 will equal to 1,2,3. Thus, we will have [[1,2,3],[1,2,3]] after the 2 loops completed!

Tim
  • 1,029
  • 2
  • 14
  • 23