Skip to main content
 首页 » 编程设计

python之检查列表 a 中的项目是否在列表 b 中找到并返回列表 c 与列表 b 在 Python 中的匹配索引

2025年05月04日14jillzhang

我有列表 a = ["string2", "string4"] 和列表 b = ["string1", "string2", "string3", "string4", "string5 "] 我想检查列表 a 中的 "string2"和 "string4"是否与列表 b 中的匹配,如果匹配,则将列表 c 附加到列表 b 中的相应索引,因此列表 c 应该是 [1,3]

到目前为止我的代码:

for x in a: 
    for y in b: 
        if x == y: 
            print (x) 

所以我设法将它们打印出来,但不知道如何获取索引。

现在这是我的问题的简单版本,我可以像这样解决它,但为了好玩,我会告诉你整个事情。

我有一个使用 nltk.word_tokenize 生成的元组列表,格式如下 [('string1', 'DT'), ('string2', 'NNP'), ( 'string3', 'NNP'), ('string4', 'NNP'), ('string5', 'VBZ'), ("string6", 'RB')] 我想检查单词(string1、string2、string3 等)在另一个单词列表(停用词列表 ex:stopwords = ["string312", "string552", string631"])中找到,如果找到我会想知道它们在我的元组列表中的索引,方法是创建另一个列表来存储这些索引,如果找不到则保持为空。

请您参考如下方法:

您可以使用 index从你的第二个列表中,同时在列表理解中迭代第一个列表的元素。

>>> a = ["string2" , "string4"] 
>>> b = ["string1" , "string2" , "string3" , "string4" , "string5"] 
>>> c = [b.index(i) for i in a] 
>>> c 
[1, 3] 

如果一个元素可能在 a 但不在 b 中,那么你可以稍微修改一下

>>> [b.index(i) for i in a if i in b] 
[1, 3]