简体   繁体   中英

How do I evaluate string lists in Python

I'm trying to make a script that evaluates a word to see whether or not its parts add up to 23 in any way (all four operations).

I've gotten it down to creating a string list of possible equations:

answerList = [12+15+12,12+15-12,12+15/12,...]

The problem I'm now getting is that I cannot get them back out of the lists in integer format to see whether or not they actually equal 23/32.

Check out the eval() function

>>> eval("12+15+12")
39
>>> eval("12+15/12")
13

Then, you can just loop through the list, calling eval on each while doing something with the result.

If you store your data like your example it will automatically convert them to integer anyway eg :

>>> answerList = [12+15+12,12+15-12,12+15/12, ...]
>>> answerList
[39, 15, 13, ...]

However, if you want to store it and print it out which equation has result 23, your need to store them as a string then use eval to convert them to int to check that it equal to 23 or not then print out the equation.

answerList = ['12+15+12','12+15-12','12+15/12']
for equation in answerList :
  if eval(equation) == 23 :
    print equation

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