Python Search Function Implementation Guide
In Python, implementing a search function is typically done using built-in data structures and algorithms. Here is a simple example:
def search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
# 测试
arr = [1, 2, 3, 4, 5]
target = 3
result = search(arr, target)
if result != -1:
print(f"目标元素 {target} 在数组中的索引为 {result}")
else:
print("目标元素不存在于数组中")
The example above is a simple linear search algorithm, which traverses each element in the array and returns its index if the target element is found, otherwise it returns -1. In fact, there are more efficient search algorithms in Python, such as binary search, you can choose the appropriate algorithm to implement the search function based on specific needs.