两个lis的Python列表理解

2024-05-19 06:23:47 发布

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

我只能用Python来理解列表

我有以下的数据结构

dataset = [sentence1, sentence2,...]
sentence = [word1, word2,...]

另外,我还有一个特殊词汇的清单

^{pr2}$

我想浏览一下special_words中的所有特殊单词,并获取与special_words一起出现在句子中的words。在

结果我想

data=[special_word1_list, special_word2_list, ...], 

,其中special_word1_list = [word1, word2, ...]

意思是word1, word2 ,...和{}一起出现在句子中

我尝试了许多不同的方法来构建列表理解,不幸的是没有成功。在

我将非常感谢任何帮助,另外,如果你知道任何关于列表理解的好文章,请把它贴在这里。在


Tags: 数据结构列表单词dataset词汇sentencelist句子
3条回答

我想你想要:

data = [sentence for sentence in data
        if any(word in special_words 
               for word in sentence)]

或者,我建议创建一个字典,将特殊单词映射到同一个句子中出现的其他单词集,作为相应的特殊单词:

{sw : {w for ds in dataset if sw in ds for w in ds if w != sw}
      for sw in special_words}
data = [
    {
        word
        for sentence in sentences
            if special_word in sentence
                for word in sentence
    }
    for special_word in special_words
]

相关问题 更多 >

    热门问题