首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果列表中有字符串,则输出列表的索引和找到哪个字符串。

如果列表中有字符串,则输出列表的索引和找到哪个字符串。
EN

Stack Overflow用户
提问于 2022-07-02 09:38:25
回答 2查看 33关注 0票数 -1
代码语言:javascript
复制
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‘

我如何才能得到输出:

代码语言:javascript
复制
blueberry was found in index: 1 of py_list
keylime was found in index: 3 of py_list
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-07-02 10:28:29

可以通过消除迟查指数的需要来改进已被接受的答案,具体如下:

代码语言:javascript
复制
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')

输出:

代码语言:javascript
复制
blueberry was found in index: 1 of py_list
keylime was found in index: 3 of py_list
票数 1
EN

Stack Overflow用户

发布于 2022-07-02 09:55:56

首先,你滥用了任意函数。当any()发现可迭代项中的一个项为True或具有True布尔值时,它接受一个可迭代项并返回True。

其次,您需要在较高层次结构的for循环中声明变量,这样它才能到达if语句中的语句,如下所示。

代码语言:javascript
复制
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")
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72838034

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档