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

Python实现判断句子中每个'def'是否在引号内的函数求助

判断'def'是否处于引号内的解决方案

Hey David, let's work through this problem together! The core idea you mentioned—checking if each 'def' position falls within a pair of quotation marks—is totally on the right track. Here's how to turn that idea into working code, plus a breakdown of the logic.

Step 1: Understand the Quotation Pairing

First, we need to group your list_quotes into consecutive pairs. Since quotes always come in pairs, your list should have an even number of elements (which yours does: [0,19,25,34] splits into (0,19) and (25,34)). Each pair represents the start and end positions of a quoted section.

Step 2: Check Each 'def' Position Against Quote Pairs

For every position in list_def, we just need to verify if it lies between the start and end of any quote pair. Important note: we use < instead of <= because the quote positions themselves are the boundaries—we want to check if the 'def' is inside the quoted text, not overlapping with the quotes.

Implementation Code (Python)

list_def = [14, 21, 31]
list_quotes = [0, 19, 25, 34]

# Group quotes into (start, end) pairs
quote_pairs = list(zip(list_quotes[::2], list_quotes[1::2]))

# Check each def position
def_in_quotes = []
for def_pos in list_def:
    is_inside = any(start < def_pos < end for start, end in quote_pairs)
    def_in_quotes.append(is_inside)

# Print results
for pos, inside in zip(list_def, def_in_quotes):
    print(f"def at position {pos}: {'inside quotes' if inside else 'not inside quotes'}")

Output for Your Example

def at position 14: inside quotes
def at position 21: not inside quotes
def at position 31: inside quotes

Why This Works

  • list_quotes[::2] grabs all even-indexed elements (start positions: 0, 25)
  • list_quotes[1::2] grabs all odd-indexed elements (end positions:19,34)
  • zip() pairs them up into tuples like (0,19)
  • The any() function checks if the 'def' position falls in any of these ranges—if yes, it returns True

If you run into edge cases (like an odd number of quote positions, or 'def' exactly on a quote boundary), we can tweak the logic, but this should handle your current scenario perfectly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:56:51