MarcinKonowalczyk
MarcinKonowalczyk

Reputation: 2788

Python: Altering code between iterations

I have a bit of code that I want to run multiple times. That seams trivial but there is a twist: I want to change the code in a specific way between iterations. For example:

A = 1
B = ['+','-','/'.'*','**']
C = []
for x in range(len(B)):
    C.append(A{B[x]}100)
print(C)

Now, I know this code doesn't work and it's not a proper Python syntax, but i't just an example of what I'd like the code to do.

Ideally I'd get C as a list where 0th element is 1 + 100, 1st element is 1 - 100, 2nd element is 1 / 100 etc. (N.b.: NOT '1 + 100' string. A result of 1 + 100 calculation - 101). Basically I want the code to change itself between iterations of loop in a defined way.

I do not want to define some lengthy if/elif statement since list B is very, very long.

Edit:

Let me give another example. This one is more relevant to my problem.

A = ['mom','dad','me','you','c']
B = ['a','b','something','nothing','cat']
for x in range(len(A)):
    C_{A[x]} = B[x]

I want to end up with 5 new variables so that:

Print(C_mom)
a
Print(C_dad)
b
Print(C_c)
cat

Again, I recognize this is not a proper python syntax and this code doesn't work.

Upvotes: 1

Views: 72

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251041

First create a dict where each string '+','*' etc point to it's corresponding method imported from operator module.

Now loop over B and fetch the corresponding method from the ops dict and pass the operands to the method.

>>> from operator import add,sub,mul,div,pow
>>> ops = {'+':add,'-':sub,'/':div, '*':mul,'**':pow}
>>> B = ['+','-','/','*','**']
>>> A = 1
>>> [ops[item](A,100) for item in B]
[101, -99, 0, 100, 1]

Use '/': operator.truediv if you want ops['/'](1,100) to return 0.01 instead of 0.

Update:

Creating dynamic variables in python is not a good idea, you should better use a dict here:

>>> A = [1,2,3,4,5]
>>> B = ['a','b','something','nothing','cat']
>>> c = {x:y for x,y in zip(A,B)}
>>> c[1]
'a'
>>> c[2]
'b'
>>> c[5]
'cat

Use globals() to create dynamic variables(don't use this method):

for x,y in zip(A,B):
    globals()['C'+str(x)] =y
...     
>>> C1
'a'
>>> C2
'b'

Upvotes: 2

Related Questions