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

时间:2011-04-14 11:50:56

标签: python list tuples

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

list =  ["the","end"]

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

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

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

感谢

2 个答案:

答案 0 :(得分:12)

>>> 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)。

答案 1 :(得分:0)

不确定这是否是你所追求的:

>>> 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,您可以决定该怎么做。

编辑:好的,克里加的方法要好得多。