J'ai un scénario dans lequel l'utilisateur peut transmettre plusieurs options. Pour chaque option transmise, j'obtiendrai le texte, puis fusionnerai finalement le texte de plusieurs options et retournerai une seule chaîne. Voici comment je le fais pour trois options que j'accepte aujourd'hui. Le code semble déjà ingérable et que j'ajouter plus d'options, la logique va empirer:meilleure façon de combiner des chaînes à partir de plusieurs options
if (len(self.options.passedin.split(",")) > 0): #multiple options were passed in
ops = self.options.passedin.split(",")
for op in ops:
if (op == "option1"):
op1_text = get_text_for_option1()
elif (op == "option2"):
op2_text = get_text_for_option2()
elif (op == "option3"):
op3_text = get_text_for_option3()
#all three were passed in
if ("option1" in ops and "option2" in ops and "option3" in ops):
op1_op2 = op1_text + " " + ' '.join(w for w in op1_text.split() if w not in op2_text.split())
op3_op1_op2 = op1_op2 + " " + ' '.join(w for w in op1_op2.split() if w not in op3_text.split())
return op3_op1_op2
#option1 and option2 were passed in
elif ("option1" in ops and "option2" in ops and "option3" not in ops):
return op1_text + " " + ' '.join(w for w in op1_text.split() if w not in op2_text.split())
#option1 and option3 were passed in
elif ("option1" in ops and "option3" in ops and "option2" not in ops):
return op1_text + " " + ' '.join(w for w in op1_text.split() if w not in op3_text.split())
#option2 and option3 were passed in
elif ("option2" in ops and "option3" in ops and "option1" not in ops):
return op2_text + " " + ' '.join(w for w in op2_text.split() if w not in op3_text.split())
Les méthodes get_text_for_option1
get_text_for_option2
get_text_for_option3
ne peuvent pas être combinés.
Pourquoi avez-vous besoin de les combiner ? – polku
Je vois des choses inutiles/incorrectes ici ('len (quelque chose)> 0' au lieu de' something', '&&' au lieu de 'and' avant l'édition,''option2 'dans ops' et 'option2 pas dans ops' pour la dernière option ...). Je suggère de prendre plus de temps pour refactoriser et améliorer tout ce que vous pouvez d'abord. – TigerhawkT3
Si j'ajoute deux options plus tard, alors la logique 'if/elif' commencera à empirer. – Anthony