How to reduce the amount of Elif

Asked

Viewed 158 times

-2

I’m starting in python and the current project (which is to apportion printers) has a lot of Elif, have any method I can reduce this in python? already I thank you.

This and the current code:

 for i in range(len(list_nome_serial_valor)): 
        lista = list_nome_serial_valor[i][0]

        if "SAME" in lista:
            same = Setores("48","SAME")
            same.adicionar_impressora(list_nome_serial_valor[i])
            setores.append(same)

        elif "PORTARIA CENTRAL" in lista or "RECEPCAO MULTIPROFISSIONAL" in lista:
            rm = Setores("40","RECEPCAO MULTIPROFISSIONAL")
            rm.adicionar_impressora(list_nome_serial_valor[i])
            setores.append(rm)

        elif "CONTABILIDADE" in lista:
            contabilidade = Setores("27","CONTABILIDADE")
            contabilidade.adicionar_impressora(list_nome_serial_valor[i])
            setores.append(contabilidade)

  #[mais elif's ...]

Obs: It separates the printer name and creates an object with all printers in the industry

  • 1

    First, do something like ('A' or 'B') in X does not check whether A or B are in X; in fact the expression will first be evaluated 'A' or 'B', who will always return 'A' and thus only check if A is in X, ignoring B. To check the two need to do A in X or B in X.

2 answers

1

I would try to move the code that is in common across all branches of if out of it (either before or after). Put all these ifs in a part function also helps.

def criar_setor(lista):
    if "SAME" in lista: return Setores("48", "SAME")
    if "PORTARIA CENTRAL" in lista or "RECEPCAO MULTIPROFISSIONAL" in lista:
        return Setores("40", "RECEPCAO MULTIPROFISSIONAL")
    if "CONTABILIDADE" in lista: return Setores("27", "CONTABILIDADE")
    # Mais um monte de ifs aqui...
    raise ValueError("Não sei")

for i in range(len(list_nome_serial_valor)): 
    lista = list_nome_serial_valor[i][0]
    setor = criar_setor(lista)
    setor.adicionar_impressora(list_nome_serial_valor[i])
    setores.append(setor)

0


I believe a lot can be refactored based on the code snippet that you provided, but for your specific self:

  • would create a code dictionary:regex
  • iterate in list_serial_value list
  • in each iteration I would iterate in the dictionary using items()
  • would run re.search with the value of the items() and the name
  • if the return is different from None (meaning match) I would execute the normal code
  • after running Windows from a break to exit the Inner loop
#Supondo que list_nome_serial_valor seja do tipo [(a,b,c),(d,e,f)...]
import re

match_dict = {
    "48": "SAME",
    "40": "(RECEPCAO MULTIPROFISSIONAL|PORTARIA CENTRA)",
    "27": "CONTABILIDADE"
}

for nome, serial, valor in list_nome_serial_valor: #outer loop
    for k, v in match_dict.items(): #inner loop
        if re.search(v, nome) != None:
            set = Setores("48","SAME")
            set.adicionar_impressora((nome, serial, valor))
            setores.append(set)
            break

I wrote this code so there may be some bug, but if you have any problem just leave a comment that I update/explain the code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.