【发布时间】:2015-03-26 23:52:30
【问题描述】:
假设我有一长串带有标点符号、空格等的列表,如下所示:
list_1 = [[the guy was plaguy but unable to play football, but he was able to play tennis],[That was absolute cool],...,[This is an implicit living.]]
我还有一个长长的列表是这样的:
list_2 =['unable', 'unquestioning', 'implicit',...,'living', 'relative', 'comparative']
对于list_1 的每个子列表,如何提取出现在list_2 中的所有单词的计数或频率?例如给定上面的列表:
list_2 =['unable', 'unquestioning', 'implicit',...,'living', 'relative', 'comparative']
[the guy was unable to play football, but he was able to play tennis]
由于无法出现在list_2 的上一个子列表中,因此该列表的计数为1。
list_2 =['unable', 'unquestioning', 'implicit',...,'living', 'relative', 'comparative']
[That was absolute cool]
由于之前的子列表中没有出现list_2的单词,所以计数为0。
list_2 =['unable', 'unquestioning', 'implicit',...,'living', 'relative', 'comparative']
[This is an implicit living.]
由于implicit 和 living 出现在list_2 的上一个子列表中,因此该列表的计数为2。
比期望的输出是[1,0,2]。
知道如何处理此任务以返回计数列表吗?在此先感谢各位。
例如:
>>> [sum(1 for word in list_2 if word in sentence) for sublist in list_1 for sentence in sublist]
错了,因为混淆了guy 和playguy 这两个词。知道如何解决这个问题吗?
【问题讨论】:
-
如果您将列表或字符串转换为单词集,那么剩下的问题就变得容易解决了。一般来说,您应该尝试发布一些需要修复/改进的特定问题的代码。
-
如果输入列表是
['this is is a test']和['is'],你想要的输出是[1]还是[2]? -
感谢您的反馈@TomDalton
[1]
标签: python arrays list tuples counter