2011-04-14 128 views
1

我有一個包含兩個詞與元組比較列出蟒蛇

list = ["the","end"] 

我有一個元組列表清單,如本

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

是否有可能系統性地去通過在每個元組bigramslist並查看列表中的兩個單詞是否與bigramlist中的任何元組匹配。如果是這樣,那麼返回true?爲了完整

感謝

+0

你在找重複嗎? – 2011-04-14 11:55:01

+3

是否(結束的)匹配(的,結束),或者這些元組是否必須以相同的順序匹配? – 2011-04-14 12:03:19

+0

是的元組必須是在相同的順序匹配 – Tom 2011-04-14 13:06:12

回答

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

+2

如果bigramslist中的順序並不重要,它應該是一個'set'而不是一個列表 - 這將加快比較。在使用'in'運算符檢查容器之前,只需執行'bigramslist = set(bigramslist)'。 – jsbueno 2011-04-14 12:41:16

+0

@jsbueno:的確,雖然經常可以首先構建一個集合,而不是建立一個列表,然後從中創建一個集合。 – delnan 2011-04-14 14:02:23

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] 
>>> 

匹配任何比較值的 - 那麼你可以決定做什麼如果列表中包含如此。

編輯:好吧,克里加的方法好多了。