You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用列表优化多条件匹配的if-elif代码实现?

Using a List to Clean Up Priority-Based String Matching

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 if name contains '22', it will match before we ever get to checking '2'—just like your first two conditionals.
  • The break statement 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 another elif line.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:42:10