将列表与python中的元组进行比较

Tom*_*Tom 1 python tuples list

我有一个包含两个单词的列表

list =  ["the","end"]
Run Code Online (Sandbox Code Playgroud)

我有一个像这样的元组列表

bigramslist = [ ("the", "end"), ("end", "of"), ("of", "the"), ("the", "world") ]
Run Code Online (Sandbox Code Playgroud)

是否有可能系统地遍历bigramslist中的每个元组,并查看列表中的两个单词是否与bigramlist中的任何元组匹配.如果是这样回归真实?

谢谢

DTi*_*ing 12

>>> L1 = ["the","end"]
>>> bigramslist = [ ("the","end"), ("end","of"), ("of","the"), ("the","world") ]
>>> tuple(L1) in bigramslist
True
Run Code Online (Sandbox Code Playgroud)

编辑完整性:

>>> bigramsset = set( [ ("the","end"), ("end","of"), ("of","the"), ("the","world") ] )
>>> L1 = ["the","end"]
>>> tuple(L1) in bigramsset
True
Run Code Online (Sandbox Code Playgroud)

正如jsbueno指出的那样,使用集合将导致O(1)搜索时间复杂度,其中搜索列表是O(n).作为附注,创建集合也是额外的O(n).

  • 如果bigramslist中的顺序无关紧要,那么它应该是一个"set"而不是一个列表 - 这将加速比较.在使用`in`运算符检查容器之前,只需执行`bigramslist = set(bigramslist)`. (2认同)