假设我们有一个包含小句子作为元素的列表。我们还有另一个列表,其中包含第一个列表的该句子中使用的一些单词。我们想找出第二个列表中的两个单词是否同时出现在第一个列表的某些句子中。
我们使用带in条件的for循环来检查句子列表中是否存在单词。然后,我们使用len函数检查是否到达列表的末尾。
list_sen = ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday'] list_wrd = ['Eggs', 'Fruits'] print("Given list of sentences: \n",list_sen) print("Given list of words: \n",list_wrd) res = [] for x in list_sen: k = [w for w in list_wrd if w in x] if (len(k) == len(list_wrd)): res.append(x) print(res)
输出结果
运行上面的代码给我们以下结果-
Given list of sentences: ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday'] Given list of words: ['Eggs', 'Fruits'] ['Eggs and Fruits on Wednesday']
在这里,我们设计了一个for循环,用于检查单词是否在包含句子的列表中,然后应用所有功能来验证确实单词在句子中是否存在。
list_sen = ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday'] list_wrd = ['Eggs', 'Fruits'] print("Given list of sentences: \n",list_sen) print("Given list of words: \n",list_wrd) res = [all([k in s for k in list_wrd]) for s in list_sen] print("\nThe sentence containing the words:") print([list_sen[i] for i in range(0, len(res)) if res[i]])
运行上面的代码给我们以下结果-
输出结果
Given list of sentences: ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday'] Given list of words: ['Eggs', 'Fruits'] The sentence containing the words: ['Eggs and Fruits on Wednesday']
我们可以采用与上述类似的方法,但要使用lambda和map函数。我们还使用拆分功能,并使用句子检查列表中所有给定单词的可用性。映射函数用于再次将此逻辑应用于列表的每个元素。
list_sen = ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday'] list_wrd = ['Eggs', 'Fruits'] print("Given list of sentences: \n",list_sen) print("Given list of words: \n",list_wrd) res = list(map(lambda i: all(map(lambda j:j in i.split(), list_wrd)), list_sen)) print("\nThe sentence containing the words:") print([list_sen[i] for i in range(0, len(res)) if res[i]])
输出结果
运行上面的代码给我们以下结果-
Given list of sentences: ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday'] Given list of words: ['Eggs', 'Fruits'] The sentence containing the words: ['Eggs and Fruits on Wednesday']