You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python列表中查找包含指定子字符串的元素索引?

解决列表中查找包含子串的元素索引问题

哦,我明白你踩的这个坑了!list.index()方法是用来找完全匹配的元素的,可不是用来查找包含指定子串的元素——这就是为啥你搜"whats"会提示"不在列表里",毕竟列表里的元素是"hello, whats up?",不是"whats"本身呀。

要实现你想要的功能,咱们可以用enumerate()遍历列表,它能同时给你返回每个元素的索引和内容,接着只要检查目标子串是否在当前元素里就行:

只找第一个匹配的索引(找到就停)

my_list = ["hello, whats up?", "my name is...", "goodbye"]
target_str = "whats"

for idx, item in enumerate(my_list):
    if target_str in item:
        print(idx)  # 输出 0
        break  # 找到第一个匹配项就退出循环

收集所有匹配的索引(多元素符合条件时)

如果列表里可能有多个元素包含目标子串,用列表推导式就能一次性把所有符合条件的索引收齐:

my_list = ["hello, whats up?", "whats your name?", "goodbye"]
target_str = "whats"

matching_indices = [idx for idx, item in enumerate(my_list) if target_str in item]
print(matching_indices)  # 输出 [0, 1]

说白了,enumerate()就是给列表里的每个元素都贴上了索引标签,这样咱们在检查子串存在性的同时,也能直接拿到对应的位置啦。

内容的提问来源于stack exchange,提问作者prayerShawl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 21:07:30