为Lis子字符串中的单词编制索引

2024-05-15 09:04:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何为列表的子字符串编制索引。 假设我们得到了清单:

shoes = ['Oxford shoes', 'Casual shoes', 'Tennis shoes', 'Oxford 
        shoes']

为了索引一个普通的列表,我会做(赋值变量)[索引值]。因此,在本例中,如果我想找到“休闲鞋”在鞋子列表中的位置,我会:

shoes[1] or shoes[-3]

但是,我该如何在鞋类列表的子字符串“休闲鞋”中使用“休闲”一词呢


Tags: or字符串列表赋值oxford我会鞋类本例
2条回答

要查找包含子字符串的字符串的索引,可以使用:

casual_index = shoes.index(next(w for w in shoes if 'Casual' in w))

这将返回:1

然后你可以拆分它,得到他们评论中提到的@Thom这个词

您只需检查字符串中是否有您想要的内容

shoes = ['Oxford shoes', 'Casual shoes', 'Tennis shoes', 'Oxford shoes']

def find_index(elements, text):
    results = []
    for i, element in enumerate(elements):
        if text in element:
            results.append(i)
    return results

print(find_index(shoes, "Casual"))
[1]

相关问题 更多 >