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

Python提取含指定单词的数组索引至新数组:问题排查与优化

Troubleshooting and Optimizing Your Python Index Collection Code

Let’s break this down step by step. First, we’ll cover the most common reasons your initial code might be failing, then look at cleaner, more Pythonic ways to get the result you want.

Common Reasons Your Code Fails

Here are the typical pitfalls that lead to incorrect or empty finalArray:

  • Using exact equality instead of membership check
    If you wrote code like this:

    array = ["I go to school", "school is fun", "hello world"]
    finalArray = []
    for i in range(len(array)):
        if array[i] == "school":
            finalArray.append(i)
    

    This only matches elements that are exactly the string "school", not elements that contain the word. You need to use the in operator instead of ==.

  • Traversing elements without tracking indices properly
    If you loop through elements directly but use array.index(element) (which breaks with duplicates):

    finalArray = []
    for element in array:
        if "school" in element:
            finalArray.append(array.index(element))  # Bad: returns first occurrence only
    

    If your array has duplicate elements containing "school", this will add the same index multiple times instead of the correct unique indices.

  • Ignoring case sensitivity
    If your array has elements like "School is great" but you’re checking for lowercase "school", the membership check will fail. You need to normalize case for consistent matching:

    if "school" not in element.lower():  # Or use element.upper() == "SCHOOL"
        continue
    
  • Forgetting to initialize finalArray
    If you tried to append to finalArray without first declaring it as an empty list (finalArray = []), you’ll get a NameError.

Better, More Pythonic Implementations

Once you’ve fixed those issues, here are two cleaner ways to build finalArray:

1. List Comprehension with enumerate

This is the most concise and readable approach in Python. enumerate gives you both the index and the element in one loop:

array = ["I go to school", "school is fun", "hello world", "High school rules"]
finalArray = [index for index, elem in enumerate(array) if "school" in elem.lower()]
# Result: [0, 1, 3]

Remove elem.lower() if you want an exact case-sensitive match.

2. Explicit for Loop with enumerate

If you prefer a more explicit loop (great for debugging or adding extra logic), this works too:

array = ["I go to school", "school is fun", "hello world", "High school rules"]
finalArray = []
for index, elem in enumerate(array):
    if "school" in elem.lower():
        finalArray.append(index)

Both methods run in O(n) time complexity (efficient for any array size) and avoid the pitfalls of common mistakes.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 06:53:03