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

Python:如何验证压缩列表中的字符串对互为子串?

Hey there! Let's fix your code to handle the substring-based pair validation you need. The original code only checks for exact matches between your (b,s) pairs and the approved ones, but we need to adjust it to account for cases where one string is a substring of the other.

Solution for Substring-Based Pair Validation

The core issue with your original code is that it uses exact pair matching (if (b,s) in zip(approved_b, approved_s)), which doesn't account for substring relationships like "alpha" ↔ "alpha 1" or "gary" ↔ "gary time". Here's the corrected approach:

b_list = ['alpha', 'beta time', 'gamma', 'ohm']
s_list = ['gary', 'paul', 'lime', 'apple']
approved_b = ['alpha 1', 'beta', 'gamma 2', 'ohm']
approved_s = ['gary time', 'zoom', 'lime time', 'appler']

br, sr = [], []

# Precompute approved pairs to avoid re-zipping in every iteration
approved_pairs = list(zip(approved_b, approved_s))

for b, s in zip(b_list, s_list):
    # Check if any approved pair meets the substring condition for both elements
    is_valid = any(
        (b in ab or ab in b) and (s in as_ or as_ in s)
        for ab, as_ in approved_pairs
    )
    if is_valid:
        br.append(b)
        sr.append(s)

print(f"br={br}")
print(f"sr={sr}")

Key Changes Explained:

  • Precompute Approved Pairs: We convert the zipped approved lists into a single list of tuples (approved_pairs) to avoid redundant work in each loop iteration.
  • Substring Check: The any() function verifies if there's at least one approved pair where:
    • Either b is a substring of ab or ab is a substring of b
    • Either s is a substring of as_ or as_ is a substring of s (we use as_ instead of as since as is a reserved keyword in Python)
  • Result Collection: Valid pairs are added to the br and sr lists as before.

Output for Your Example Input:

When you run this code, the output will be:

br=['alpha', 'gamma', 'ohm']
sr=['gary', 'lime', 'apple']

Note: This includes the fourth pair ('ohm', 'apple') because 'ohm' matches its approved counterpart exactly, and 'apple' is a substring of 'appler'. If this wasn't intended, you could adjust the logic to require a specific direction of substring (e.g., only allow the approved string to contain the input string), but based on your stated requirement of recognizing mutual substring equivalence, this is the correct result.

内容的提问来源于stack exchange,提问作者Gary Kim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:36:25