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.
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
bis a substring ofaborabis a substring ofb - Either
sis a substring ofas_oras_is a substring ofs(we useas_instead ofassinceasis a reserved keyword in Python)
- Either
- Result Collection: Valid pairs are added to the
brandsrlists 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

