help in a list comprehension python with double for

1

I have these dictionaries defined

SustantivoMS = {#diccionario sustantivo masculino singular
    'perro':'PERRO',
    'gato':'GATO',
    'arbol':'ARBOL'   
}
ArticuloMS = {#diccionario para articulos masculinos singular
    'el':'EL',
    'un':'UN'
}

and this way of virificar the combinations of noun and article

cont = 0
for articuloms in ArticuloMS:
    for sustms in SustantivoMS:
        if (ArticuloMS[articuloms] == oracion[0] and SustantivoMS[sustms] == oracion[1]):
            cont = 1
            break

I would like to know if this mode can be simplified in a list comprehension, I do not manipulate them very well

the sentence is a list may well be

oracion=['EL','PERRO'] como ejemplo, pero claro son palabras del diccionario
    
asked by Efrainrodc 10.05.2017 в 16:51
source

1 answer

2

As you well say using "list comprehension" you get a more compact code and in some cases more readable. For your example, the list of combinations can be generated as follows:

[(a,s) for a in ArticuloMS for s in sustantivoMS]

if then you have to do something with it just

for c in [(a,s) for a in ArticuloMS for s in sustantivoMS]:
    pass

And for the same price, the other way is using the Cartesian product routine

import itertools
for c in itertools.product(ArticuloMS,sustantivoMS):
    pass
    
answered by 10.05.2017 / 17:09
source