在python中比较列表与元组

2024-06-01 21:43:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个单子,里面有两个词

list =  ["the","end"]

我有一个这样的元组列表

^{pr2}$

有没有可能系统地检查bigramslist中的每个元组,看看列表中的两个单词是否与bigramlist中的任何一个元组匹配。如果是这样,返回真值?在

谢谢


Tags: the列表单词list单子end元组系统地
2条回答
>>> L1 = ["the","end"]
>>> bigramslist = [ ("the","end"), ("end","of"), ("of","the"), ("the","world") ]
>>> tuple(L1) in bigramslist
True

编辑完整性:

^{pr2}$

正如jsbueno指出的,使用集合将导致O(1)搜索时间复杂性,其中搜索列表时是O(n)。作为旁注,创建集合也是一个附加的O(n)。在

不确定这是否是你想要的:

>>> list = ["the", "end"]
>>> bigramslist = [ ("the", "end"), ("end", "of"), ("of", "the"), ("the", "world") ]
>>> def check(list, biglist):
...     return [(list[0], list[1]) == big for big in biglist]
... 
>>> check(list, bigramslist)
[True, False, False, False]
>>> 

匹配任何比较的值-然后您可以决定如果该列表包含true,该怎么做。在

编辑:好吧,克里格的方法好多了。在

相关问题 更多 >