-1

I am trying to start and append new lists inside a loop using iterator. I tried to use dictionary idea from this answer.

Here is the snippet of my code, you can ignore the details of the code. If the if condition is satisfied I need to append values of i in a specific list, which will be like patch12,patch53 etc:

import math as m

d = {}

for i in range(0,10):

     for j in range(0, 10):

          if((m.floor(vector[upper_leaflet[i],0:1]) <= xx[j][0]) & (m.floor(vector[upper_leaflet[i],0:1]) < yy[j][0])):

              d["patch{}{}".format(xx[j][0],yy[j][0])].append(i)

Output should be something like if I print patch52 = [ 1, 5, 9 ,10] What would be the correct way to do perform this?

Community
  • 1
  • 1
Grayrigel
  • 3,474
  • 5
  • 14
  • 32

2 Answers2

2

You are trying to create dynamic variables with name patch12 or patch53 etc. This can not be done just by formatting a string. Look at this thread where dynamic variable creation is explained.

However, its not a good programming practice. Correct solution could be to use a dictionary or a list. example:

patches = {}
for i in range(0,10):

     for j in range(0, 10):

          if((m.floor(vector[upper_leaflet[i],0:1]) <= xx[j][0]) & (m.floor(vector[upper_leaflet[i],0:1]) < yy[j][0])):

              key_name = "patch{}{}".format(xx[j][0],yy[j][0])
              #if key already exists, append to that list, if not create new list
              if key_name in patches:
                    key_value = patches[key_name]
              else:
                    key_value = []
              #appending newly value ..
              key_value.append(i)
              patches[key_name] = key_value

Further , in your program when you need to use this data, either your can iterate through dictionary to find out all keys ex:

for patch in patches:
    do something...

or you can directly access value of a particular key (ex: patch52 by

value = patches['patch52'] 

which will give you a list of values corresponding to patch52 ex:

print(patches['patch52'])
[1,4,7,9]
Community
  • 1
  • 1
Vijayakumar Udupa
  • 1,115
  • 1
  • 6
  • 15
0

Using a collections.defaultdict makes things easier:

import math as m
from collections import defaultdict

d = defaultdict(list)
for i in range(0,10):
     for j in range(0, 10):
          if ((m.floor(vector[upper_leaflet[i],0:1]) <= xx[j][0]) & (m.floor(vector[upper_leaflet[i],0:1]) < yy[j][0])):
              d["patch{}{}".format(xx[j][0],yy[j][0])].append(i)
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118