如何在Python中避免大量使用if/elif语句实现元素匹配与条件搜索?
if/elif Chains with Condition Mapping Hey there! Dealing with 20+ if/elif statements is messy and a pain to maintain—let's refactor this into a much cleaner, scalable solution using condition mappings. The core idea is to store your conditions and their corresponding actions in a structured list, then loop through that list to find a match instead of writing repetitive conditional blocks.
Step 1: Refactor Your Condition Logic
First, we'll eliminate the long if/elif chain by grouping each condition with its target action. Since many of your checks share the 0 <= self.x_1 <= 16 range, we can extract that as a top-level condition to avoid repeating it across every check:
def find_match(self): self.y_1 = 0 self.x_1 = 0 for f in self.extrovert: q3 = tk.simpledialog.askstring(title="Please type 'y','dmt','ext'", prompt=f) if q3 == "y": self.x_1 += 1 elif q3 == "dmt": self.x_1 += 1.5 elif q3 == "ext": self.x_1 += 2 # Handle the shared x_1 range first if 0 <= self.x_1 <= 16: # Define all y_1 ranges paired with their corresponding character3 index y_condition_mappings = [ (2.25 <= self.y_1 < 3, 5), (1.5 <= self.y_1 < 2.25, 6), (0 <= self.y_1 < 1.5, 7), # Add your 20+ other conditions here in order # Example: (3 <= self.y_1 < 4, 8), (4 <= self.y_1 < 5, 9), etc. ] # Loop through mappings to find the first matching condition for condition, char_index in y_condition_mappings: if condition: with open("Draft.txt", mode="a") as dr: dr.write(f"Specific:\n {self.character3[char_index]}") break # Exit once we find a match to avoid unnecessary checks else: # Optional: Handle cases where x_1 is outside the expected range messagebox.showinfo("Info", "x_1 is outside the 0-16 range")
Why This Is Better:
- Maintainability: Adding or modifying conditions only requires updating the
y_condition_mappingslist—no need to rewrite a long chain ofif/elifstatements. - Readability: All your logic is grouped in one place, making it easy to see which ranges map to which character values at a glance.
- Scalability: If you ever need to add more conditions later, just append a new tuple to the list instead of digging through a block of conditional code.
Bonus: Handle Complex Cross-Range Conditions
If your logic expands to include different x_1 ranges paired with y_1 checks, you can scale the mapping to include full condition expressions:
full_condition_mappings = [ ((0 <= self.x_1 <= 16) and (2.25 <= self.y_1 < 3), 5), ((0 <= self.x_1 <= 16) and (1.5 <= self.y_1 < 2.25), 6), ((17 <= self.x_1 <= 32) and (2.25 <= self.y_1 < 3), 8), # Add all other cross-x/y conditions here ] for condition, char_index in full_condition_mappings: if condition: with open("Draft.txt", mode="a") as dr: dr.write(f"Specific:\n {self.character3[char_index]}") break
This approach keeps your code clean and avoids the "wall of if/elif" problem entirely.
内容的提问来源于stack exchange,提问作者ugur




