Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python:: how to insert %d into variable when defining a function

Tags:

python-2.7

How can you insert %d into a variable inside a def code so that the variables change according to the parameters given to the function?

def ratio(iterA, iterB):
   a=0.0
   b=0.0
   for i in range(20000):
       if (data2.iter%d[i] % iterA) < 0.2:
           if (data2.iter%d[i] % iterB) < 0.2:
               a += 1
           else:
               b += 1
   return a/b

This function is currently giving off errors of sorts. How can get to have data2.iter~ input variable change according the parameters I give which are iterA and iterB? For example if I give iterA as 1 and iterB as 15, then the resulting code would hopefully be computed as

a1=0.0
b1=0.0
for i in range(20000):
    if data2.iter1[i] < 0.2:
        if data2.iter15[i] < 0.2:
            a1 += 1
    else:
        b1 += 1
print(a1/b1)

Thanks in advance.

like image 556
Yongjin Kim Avatar asked Dec 07 '25 05:12

Yongjin Kim


1 Answers

You want data2 to be a two-dimensional array. Then you can use:

if data2[iterA][i] < 0.2:
     if data2[iterB][i] < 0.2:
         #...

Ok, ok. If you really need to do this, getattr(obj, name) is what you are looking for. Ie)

if getattr(data2, 'iter%d' % iterA)[i] < 0.2:
    #....

But don’t do this lookup 20000 times! Move it before the loop:

listA = getattr(data2, 'iter%d' % iterA)
#...
for i in range(20000):
    if listA[i] < 0.2:
        #...
like image 87
AJNeufeld Avatar answered Dec 09 '25 20:12

AJNeufeld