Compare elements of a character list with a character input

Viewed 22

I have a question, I have a character list similar to this:

 letras_lista = ['gcjcf', 'afadd', 'ibfah', 'ihdha', 'cdigc', 'kaaci', 'ihiga', 'jbjji', 'hbjjj', 'bcdjg', 'ieika']

And I have a two character input like this:

 orden = 'ah'

For this I created this code:

 cont = 0
for i in letras_lista:#lista que puse de ejemplo
    lista = [i]
    for x in lista:
        if orden in x:#patron a comparar
            cont +=1
print(cont)

Could you tell me if there is a way to optimize the code, I am new to programming and I don't know many ways to do it. Beforehand thank you very much

2 Answers

A very simple way is to take advantage of the fact that bool is a subclass of int, and sum over the condition:

cont = sum(orden in x for x in letras_lista)

Here is a step by step way to get from your implementation to mine:

First, notice that your inner loop is iterating over a list of length 1. Not only that, but you artificially constructed this list lista. That means that you can get rid of lista and the inner loop, and just run the conditional:

cont = 0
for i in letras_lista:
    if orden in i:
        cont += 1

Now notice that the boolean value orden in i is equivalent to what you want to add to cont. Since True == 1 in python, and False == 0, you can write

cont = 0
for i in letras_lista:
    cont += (orden in i)

Hopefully it is now clear how you can place the boolean condition directly into the sum call.

print(len([i for i in letras_lista if orden in i]))

Related