Tom
Tom

Reputation: 215

comparing lists with tuples in python

I have a list containing two words

list =  ["the","end"]

I have a list of tuples 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

Upvotes: 1

Views: 4335

Answers (2)

dting
dting

Reputation: 39287

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

Upvotes: 13

TyrantWave
TyrantWave

Reputation: 4663

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.

Upvotes: 0

Related Questions