Skip to main content
 首页 » 编程设计

python之在 python 中比较列表和元组

2025年05月04日9sharpest

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

list =  ["the","end"] 

我有一个这样的元组列表

bigramslist = [ ("the", "end"), ("end", "of"), ("of", "the"), ("the", "world") ] 

是否可以系统地遍历二元组列表中的每个元组,并查看列表中的两个词是否与二元组列表中的任何元组相匹配。如果是,则返回 true?

谢谢

请您参考如下方法:

>>> L1 = ["the","end"] 
>>> bigramslist = [ ("the","end"), ("end","of"), ("of","the"), ("the","world") ] 
>>> tuple(L1) in bigramslist 
True 

为完整性编辑:

>>> bigramsset = set( [ ("the","end"), ("end","of"), ("of","the"), ("the","world") ] ) 
>>> L1 = ["the","end"] 
>>> tuple(L1) in bigramsset 
True 

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