py_list = ['Big apple pie','Small blueberry Pie','Cold Cherry Pie','Hot keylime pie']
keywords = ['blueberry','keylime']
for text in py_list:
if any(xs in text for xs in keywords):
itemlist = (py_list.index(text))
print(xs,"was found in index: ", itemlist " of py_list")回溯(最近一次调用):NameError:在第7行中没有定义名称'xs‘
我如何才能得到输出:
blueberry was found in index: 1 of py_list
keylime was found in index: 3 of py_list发布于 2022-07-02 10:28:29
可以通过消除迟查指数的需要来改进已被接受的答案,具体如下:
py_list = ['Big apple pie','Small blueberry Pie','Cold Cherry Pie','Hot keylime pie']
keywords = ['blueberry','keylime']
for i, s in enumerate(py_list):
for k in keywords:
if k in s:
print(f'{k} was found in index: {i} of py_list')输出:
blueberry was found in index: 1 of py_list
keylime was found in index: 3 of py_list发布于 2022-07-02 09:55:56
首先,你滥用了任意函数。当any()发现可迭代项中的一个项为True或具有True布尔值时,它接受一个可迭代项并返回True。
其次,您需要在较高层次结构的for循环中声明变量,这样它才能到达if语句中的语句,如下所示。
py_list = ['Big apple pie', 'Small blueberry Pie', 'Cold Cherry Pie', 'Hot keylime pie']
keywords = ['blueberry', 'keylime']
for text in py_list:
for xs in keywords:
if xs in text:
itemlist = (py_list.index(text))
print(xs, "was found in index: ", itemlist, " of py_list")https://stackoverflow.com/questions/72838034
复制相似问题