Python提取含指定单词的数组索引至新数组:问题排查与优化
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
inoperator instead of==.Traversing elements without tracking indices properly
If you loop through elements directly but usearray.index(element)(which breaks with duplicates):finalArray = [] for element in array: if "school" in element: finalArray.append(array.index(element)) # Bad: returns first occurrence onlyIf 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" continueForgetting to initialize
finalArray
If you tried to append tofinalArraywithout first declaring it as an empty list (finalArray = []), you’ll get aNameError.
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

