I have a list containing two words
list = ["the","end"]
I have a list of tuple开发者_如何学运维s such as this
bigramslist = [ ("the", "end"), ("end", "of"), ("of", "the"), ("the", "world") ]
Is it possible to systematically go through each tuple in the bigramslist and see if both words in the list match any of the tuples in the bigramlist. And if so return true?
thanks
>>> L1 = ["the","end"]
>>> bigramslist = [ ("the","end"), ("end","of"), ("of","the"), ("the","world") ]
>>> tuple(L1) in bigramslist
True
edit for completeness:
>>> bigramsset = set( [ ("the","end"), ("end","of"), ("of","the"), ("the","world") ] )
>>> L1 = ["the","end"]
>>> tuple(L1) in bigramsset
True
as jsbueno pointed out, using a set will result in a O(1) search time complexity where as searching the list is O(n). As a side note creating the set is also an additional O(n).
Not sure if this is what you're after:
>>> 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]
>>>
Matches any of the compared values - you can then decide what to do if that list contains true.
Edit: Ok, kriegar's method is a lot better.
精彩评论