问题:利用字符串中的任何单词来查找列表中的项目并识别项目或返回索引。
您好,我一直在搜索此网站和其他网站,以找到解决我问题的方法。我找到的解决方案成功地确定了列表中是否有一个项目,
示例:
any(word in str1 for word in List)
但这只返回true或false,并使用命令
print word
返回错误
我需要一个可以找到列表项并打印项目的解决方案,或者在列表中提供索引。
我正在使用它作为AI的项目,它具有预先形成数学方程的能力。为此,它需要能够定位不仅是标准“+, - ,*,/”而且还有单词格式的运算符。例如,“加号,减号等”找到后,程序可以使用eval()可以处理的适当标准运算符简单地替换字符串中的项目。
从项目中重新应用示例代码:
from __future__ import division
import re
from math import *
Listopp = ["+","-", "*","/"]
Listadd = ["add","plus"]
Listsub = ["subtract","minus"]
Listmult = ["times","multiply","x"]
Listdivide = [ "divide","over"]
Listmath =Listopp + Listadd + Listsub + Listmult + Listdivide
try:
str1 = raw_input("what is your math problem?")
if (any(word in str1 for word in Listmath) and re.findall(r"[-+]?\d*\.\d+|\d+",str1) != []):
# here is where the solution need to be placed
opp = Listmath.index(any(word in str1))
# needs to be identified or indexed
#Replaced with standard operators
if (opp in Listdivide):
str1 = str1.replace( opp ,"/")
if (opp in Listmult):
str1 = str1.replace( opp ,"*")
if (opp in Listsub):
str1 = str1.replace( opp ,"-")
if (opp in Listadd):
str1 = str1.replace( opp ,"+")
if (opp in Listopp):
pass
math = eval(str1)
if not float(math).is_integer():
print "rounded"
result = round(math, 3)
else:
print "real"
result = math
print result
else:
print "No suitable math problems found."
except Exception as e:
print e
非常感谢您对此代码的任何帮助或建议。
答案 0 :(得分:0)
我将忽略有关您的AI项目的部分,因为它不是MCVE。我想你的问题的第一部分是,所以我将告诉你如何使用word in str1
查找列表中的项目以及满足您给出的条件(numpy.where
)的项目和索引:
import numpy as np
List = ["add", "bolt", "dead", "bolter", "test"]
str1 = "bolter"
items = [word in str1 for word in List]
print items
indices = np.where(items)[0]
print indices
此代码段将输出:
[False, True, False, True, False]
[1, 3]
建议:不要使用大写字母表示List
之类的变量。我保留了这样的答案,因为我希望你能够轻松地遵循我的解决方案。通常大写字母表示类名,因此大写变量使得您的代码更难以让其他Python程序员阅读和理解。这只是Python社区中的一种风格规范。
希望这有帮助!
答案 1 :(得分:0)
您可以使用next()
。第一个参数是迭代器,如果迭代器已经用尽,则第二个(可选)参数是默认值。以下是显示next()
的不同用法的Python会话:
>>> my_list = [4, 6, 1, 4, 1]
>>> any(x > 4 for x in my_list)
True
>>> next(x for x in my_list if x > 4)
6
>>> next(i for i, x in enumerate(my_list) if x > 4)
1
>>> next(i for i, x in enumerate(my_list) if x > 6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> default = 4
>>> next((i for i, x in enumerate(my_list) if x > 6), default)
4
>>> next((i for i, x in enumerate(my_list) if x > 4), default)
1