\$\begingroup\$
\$\endgroup\$
1
I currently have the following piece of code in place that attempts to find matches within a list, based on a priority system:
possible_combinations = ["ABC", "AB", "A", "D"]
if len(possible_combinations) >= 1:
chosen_combination = [comb for comb in possible_combinations if ("A" in comb) and ("C" in comb)]
if (len(chosen_combination) == 0):
chosen_combination = [comb for comb in possible_combinations if ("A" in comb)]
if (len(chosen_combination) == 0):
chosen_combination = [comb for comb in possible_combinations if ("C" in comb)]
if (len(chosen_combination) == 0):
raise ValueError(f"No match found.")
print(chosen_combination)
['ABC']
Is there any way I could refactor this code to get rid of these if-statements, and thereby make my code look nicer?
asked Nov 4, 2020 at 17:22
-
1\$\begingroup\$ perhaps explain why/what, there might be completely different way to solve the problem \$\endgroup\$hjpotter92– hjpotter922020年11月04日 17:48:44 +00:00Commented Nov 4, 2020 at 17:48
1 Answer 1
\$\begingroup\$
\$\endgroup\$
3
You could do something like this:
possible_combinations = ["ABC", "AB", "A", "D"]
combs = [("A","C"),("A",),("C",)]
for comb in combs:
chosen_comb = [x for x in possible_combinations if all([y in x for y in comb])]
if len(chosen_comb) > 0:
break
print(chosen_comb)
answered Nov 4, 2020 at 18:01
-
4\$\begingroup\$ Are you sure that this:
("A","C"),("A"),("C")
is your intent? The first parens make a tuple, and the second and third do not. \$\endgroup\$Reinderien– Reinderien2020年11月04日 18:33:01 +00:00Commented Nov 4, 2020 at 18:33 -
\$\begingroup\$ It doesn't really matter here, but you are right. What I meant was
[("A","C"),("A",),("C",)]
. I corrected it. \$\endgroup\$Tom Gebel– Tom Gebel2020年11月04日 19:37:16 +00:00Commented Nov 4, 2020 at 19:37 -
\$\begingroup\$ Looks quite nice. Thx! \$\endgroup\$Menno Van Dijk– Menno Van Dijk2020年11月05日 08:39:59 +00:00Commented Nov 5, 2020 at 8:39
lang-py