问题描述
|
我有一个包含两个单词的列表
list = [\"the\",\"end\"]
我有一个这样的元组列表
bigramslist = [ (\"the\",\"end\"),(\"end\",\"of\"),(\"of\",\"the\"),(\"the\",\"world\") ]
是否有可能系统地遍历bigramslist中的每个元组,并查看列表中的两个单词是否与bigramlist中的任何元组匹配。如果是,则返回true?
谢谢
解决方法
>>> L1 = [\"the\",\"end\"]
>>> bigramslist = [ (\"the\",\"end\"),(\"end\",\"of\"),(\"of\",\"the\"),(\"the\",\"world\") ]
>>> tuple(L1) in bigramslist
True
编辑完整性:
>>> bigramsset = set( [ (\"the\",\"world\") ] )
>>> L1 = [\"the\",\"end\"]
>>> tuple(L1) in bigramsset
True
正如jsbueno指出的那样,使用集合将导致O(1)搜索时间复杂度,其中搜索列表为O(n)。作为附带说明,创建集合也是一个额外的O(n)。
,不确定这是否是您所追求的:
>>> list = [\"the\",\"world\") ]
>>> def check(list,biglist):
... return [(list[0],list[1]) == big for big in biglist]
...
>>> check(list,bigramslist)
[True,False,False]
>>>
匹配任何比较值-如果该列表包含true,则可以决定要怎么做。
编辑:好的,克里格的方法要好得多。