gho
gho

Reputation: 171

multiple iteration for finding shared items in two lists

I have the following two lists:

list1 = [(('diritti', 'umani'), 'diritto uomo'), (('sgomberi', 'forzati'), 'sgombero forza'), (('x', 'x'), 'x x'), ...] ## list of tuples, each tuple contains term and lemma of term

list2 = ['diritto uomo', 'sgombero forza'] ### a small list of lemmas of terms

The task is to extract from the list1 the terms whose lemmas are present in the list2. note that one element in list2 can share the lemma with more than one term in list1, so for every item in list2 I need to find its shared items in list1. I tried this code:

result = []
for item in list2:
     for x in list1:
            for i, ii in x:
                    if item.split()[0] in ii or item.split()[1] in ii : 
                            result.append(i)

This code takes a long time to do the task, can someone suggest another way to do this. Thanks

Upvotes: 0

Views: 48

Answers (1)

Kasravnd
Kasravnd

Reputation: 107347

If you just want to match the equal lemmas you don't need to split your words and check the membership you can simply use == operation within a list comprehension:

>>> [item for item, lemm in list1 for w in list2 if w == lemm]
[('diritti', 'umani'), ('sgomberi', 'forzati')]

Otherwise by splitting the lemmas and membership checking within list1's lemmas it won't give you any result.

Upvotes: 2

Related Questions