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

标签 python list nltk

我有列表 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]

关于python - 检查列表 a 中的项目是否在列表 b 中找到并返回列表 c 与列表 b 在 Python 中的匹配索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30808083/

相关文章:

c# - 在 C# 中对由字符串组成的列表中的一些元素求和

python - Python 斯坦福解析器 : Output Format

python - 使用 FOR 循环时如何在 item.add_css() 中编写正确的 CSS?

python - 尝试解决项目 Euler 时 python 运行时间非常慢。不确定是python还是慢速算法

python - 随机内存缓存调用需要非常长的时间

python - 停止在 python 中打印 'no matches'

python-2.7 - NLTK程序包估计(字母组合)的困惑

python - 从 Sublime Text 2 运行 .py 文件

list - 在 Robot Framework 中,列表变量和包含列表的标量变量有什么区别?

python - 在单个循环中追加列表的 Pithonic 方法