简体   繁体   中英

Defining and appending in new list inside a loop using iterator (python)

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?

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]

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)

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