简体   繁体   中英

Python: Mathematical Operations using Operators from a list

Say I have a list with mathematical operators in it, like this

operators = ['+','-','*','/']

And I am taking a random operator from here, like this

op = random.choice(operators)

If I take two numbers, say 4 and 2, how can I get Python to do the mathematical operation (under the name 'op') with the numbers?

You better do not specify the operators as text . Simply use lambda expressions , or the operator module:


import random

operators = [operator.,operator.,operator.,operator.]
op = random.choice(operators)

You can then call the op by calling it with two arguments, like:

result = 

For example:

>>> import operator
>>> import random
>>> 
>>> operators = [operator.add,operator.sub,operator.mul,operator.floordiv]
>>> op = random.choice(operators)
>>> op
<built-in function sub>
>>> op(4,2)
2

So as you can see, the random picked the sub operator, so it subtracted 2 from 4 .

In case you want to define an function that is not supported by operator , etc. you can use a lambda-expression, like:

operators = [operator.add,]

So here you specified a function that takes the parameters x and y and calculates x+2*y (of course you can define an arbitrary expression yourself).

You can use eval if you are absolutely certain that what you are passing to it is safe like so:

num1 = 4
num2 = 2
operators = ['+','-','*','/']
op = random.choice(operators)
res = eval(str(num1) + op + str(num2))

Just keep in mind that eval executes code without running any checks on it so take care. Refer to this for more details on the topic when using ast to do a safe evaluation.

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