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

Python数据集多匹配逻辑优化:新增混合匹配场景需求

Hey Brian, let's fix that mixed-match scenario you're dealing with. Your original code works great when only one set has a match, but it misses cases where both sets are present in your codes array. Here's how you can adjust it to catch all three scenarios:

Original Code Limitation

a = '31' 
b = '' 
c = '' 
d = '' 
codes = [a, b, c, d] 
set_one = ('07', '10', '17', '31') 
set_two = ('01','02','03','04','05','06','08') 

if any(s in test for test in codes for s in set_one): 
    result = '"ONE"' 
elif any(s in test for test in codes for s in set_two): 
    result = '"TWO"' 
else: 
    result = 'NULL' 
print(result)

Problem: When codes contains elements from both set_one and set_two (e.g., ['07','01','','']), this code will return "ONE" immediately due to if/elif priority, and fails to detect the mixed match scenario.

Improved Code (Supports Mixed Match Detection)

a = '01' 
b = '' 
c = '' 
d = '' 
codes = [a, b, c, d] 

one_match = 0 
two_match = 0 

set_one = ('07', '10', '17', '31', 'CO', '12', '13', '25', '55', 'ZN', 'Z3', 'Z2') 
set_two = ('01','02','03','04','05','06','08','11','14','15','16','18','19','20') 

# Check each set's match status separately
if any(s in test for test in codes for s in set_one): 
    one_match = 1 
if any(s in test for test in codes for s in set_two): 
    two_match = 1 

# Determine result based on combined match status
if one_match == 1 and two_match == 1: 
    result = "MIX" 
elif one_match == 1: 
    result = "ONE ONLY" 
elif two_match == 1: 
    result = "TWO ONLY" 
else: 
    result = 'NULL' 

print(result)

Logic Breakdown

  • We use two separate variables (one_match and two_match) to track if each set has a match, instead of using mutually exclusive if/elif checks. This lets us capture both matches when they occur.
  • The final conditional checks the combination of these flags to return the correct result:
    • Both flags set → mixed match, return "MIX"
    • Only one_match set → return "ONE ONLY"
    • Only two_match set → return "TWO ONLY"
    • Neither set → return "NULL"

This adjustment ensures all possible matching scenarios are handled accurately.

内容的提问来源于stack exchange,提问作者Brian Powell

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:00:00