如何用列表优化多条件匹配的if-elif代码实现?
Absolutely, your proposed list structure is a perfect replacement for that unwieldy if-elif chain! It’s way more maintainable (you can easily add/remove pairs without messing with nested conditionals) and preserves the critical priority order you need—since we’ll check each entry in the list from top to bottom, just like your original code.
Here’s how to implement it:
First, define your list of match patterns and corresponding values:
match_list = [['22', 'this'], ['35', 'that'], ['2', 'another'], ['5', 'one']]
Then, loop through each pair and check for a match. As soon as we find one, assign the value and break the loop to ensure the first (highest priority) match is used:
x = None # Set a default value if no matches are found for pattern, value in match_list: if pattern in name: x = value break
Why this works exactly like your original code:
- We check
'22'first, so ifnamecontains'22', it will match before we ever get to checking'2'—just like your first two conditionals. - The
breakstatement ensures we stop searching once we find the first match, preventing lower-priority patterns from overwriting the result. - Adding new patterns is as simple as appending (or inserting) a new
[pattern, value]pair to the list, which is way cleaner than adding anotherelifline.
If you need to handle edge cases (like case-insensitive matches), you can adjust the condition inside the loop—for example: if pattern.lower() in name.lower().
内容的提问来源于stack exchange,提问作者Basj

