How do I compare Trigram-word-combinations of two lists and return same combinations in Python?

57 views Asked by At

we basically want to compare two lists if the same word-combinations occur. Our Trigram-Code brought us something like this:

e.g. (these are type "tuple")

List1 = 
(('I', 'want', 'this'),456)
(('What', 'is', 'this') , 25)


List2 = 
(('this', 'is', 'what'), 12)#this one should not count, because the order is different
(('I', 'want', 'this'), 9)

The numbers behind each list show how often these trigram-combinations occured in our DataFrame, maybe you have to delete them first?

List3 = Trigram-Word-Combinations that occur in List 1 AND List 2

    Result should be  "'I', 'want', 'this'"

Thank you in advance

2

There are 2 answers

0
Milan Lakhani On BEST ANSWER

List3 = [ L1phrase[0] for L1phrase in List1 if L1phrase[0] in [L2phrase[0] for L2phrase in List2] ]

You can do nested list comprehension

0
a_guest On

You can use set intersection and only use the tuple of words:

>>> {x[0] for x in List1} & {x[0] for x in List2}
{('I', 'want', 'this')}