0

I have a list of counters in my code and if it is possible I'd like to avoid to write an if condition for each of them.

I figured out the following solution in python 3, but it doesn't works.... how to?

def myfunc():
    ...
    ...
    for a in list1:

         <do something>
         for b in list2:
             a=0
             b=0
             c=0                
             <do something>

                  for c in list3:

                       <do something>

                        if <condition> is true>:

                            for element in a list:

                            <do something>

                                  for i in ['a', 'b', 'c']:
                                      if element == i:
                                      i += 1    

I don't want to create variables on fly: I need this list of counters (placed inside another loop function) to be increased when match element in the list. What may be relevant to say is that this list of counters is placed inside a function and after a series of nested loops

Ignus
  • 139
  • 1
  • 8
  • 4
    What do you mean it doesnt work? what is expected? Please make your question a Minimal, Complete, and Verifiable example [M.C.V E](https://stackoverflow.com/help/mcve). Also check [how to ask question](https://stackoverflow.com/help/how-to-ask) to make your post answerable. – Morse Jun 08 '18 at 13:02

1 Answers1

1

Is this what you want:

def myfunc():
     a=0
     b=0
     c=1
     l = [a,b,c]
     d=locals()
     for element,i in list(zip(l,['a','b','c'])):
          d[i]=d[i]+1
     print(d['a'])
     print(d['b'])
     print(d['c'])
myfunc()

Output:

1
1
2
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • Yes, this is exactely what I need but when I put this solution inside my code I get a KeyError on the very first element. Regard this I edited OP in order to clarify my environment and my intent – Ignus Jun 08 '18 at 14:01
  • I think this will also have some unexpected behaviour, since you are comparing the value of `element` and `globals()[i]` not the actual object they refer to. You could use `is` instead of `==` but for small integers, `is` and `==` are equivalent (due to the way python handles small integers). Try setting a,b,c to 0,1,0 respectively and you will get an output of 2,2,2. – tim-mccurrach Jun 08 '18 at 14:15
  • 1
    Notice also by writing `globals()[i] += 1`, you are re-assigning those variables, so the variables `a,b,c` will no longer refer to the same thing as the elements of the list 'l' – tim-mccurrach Jun 08 '18 at 14:19
  • @Ignus Your right i will edit my answer – U13-Forward Jun 08 '18 at 22:52