📅  最后修改于: 2023-12-03 15:40:26.287000             🧑  作者: Mango
在编写程序时,常常需要在数组中查找元素并进行修改。这个过程可以分为两个步骤:查询和修改。下面我们就一起来看看如何实现这个功能。
循环遍历数组,逐个比较数组元素,如果找到目标元素,则返回其下标。
def search(nums, target):
for i in range(len(nums)):
if nums[i] == target:
return i
return -1 # 未找到目标元素
如果数组是有序的,那么可以采用二分查找的方法,时间复杂度可以达到O(logn)。
def binary_search(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 # 未找到目标元素
如果我们已经知道目标元素的下标,那么可以直接修改数组。
def modify(nums, idx, val):
nums[idx] = val
return nums
如果要批量修改数组中的元素,可以使用Python中的列表推导式或map函数。
# 利用列表推导式进行修改
def modify_list(nums, targets, new_vals):
nums = [new_vals[i] if nums[j] == targets[i] else nums[j] for j in range(len(nums)) for i in range(len(targets))]
return nums
# 利用map函数进行修改
def modify_map(nums, targets, new_vals):
def change(val):
return new_vals[targets.index(val)] if val in targets else val
return list(map(change, nums))
我们来看一个完整的示例,演示如何查询并修改数组中的元素。
def search(nums, target):
for i in range(len(nums)):
if nums[i] == target:
return i
return -1
def binary_search(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
def modify(nums, idx, val):
nums[idx] = val
return nums
def modify_list(nums, targets, new_vals):
nums = [new_vals[i] if nums[j] == targets[i] else nums[j] for j in range(len(nums)) for i in range(len(targets))]
return nums
def modify_map(nums, targets, new_vals):
def change(val):
return new_vals[targets.index(val)] if val in targets else val
return list(map(change, nums))
if __name__ == '__main__':
nums = [1,2,3,4,5,6,7,8,9,10]
idx = search(nums, 5)
nums = modify(nums, idx, 55)
print(nums)
nums = [1,2,3,4,5,6,7,8,9,10]
idx = binary_search(nums, 7)
nums = modify(nums, idx, 77)
print(nums)
nums = [1,2,3,4,5,6,7,8,9,10]
targets = [3,6,9]
new_vals = [33,66,99]
nums = modify_list(nums, targets, new_vals)
print(nums)
nums = [1,2,3,4,5,6,7,8,9,10]
targets = [3,6,9]
new_vals = [33,66,99]
nums = modify_map(nums, targets, new_vals)
print(nums)
输出:
[1, 2, 3, 4, 55, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 77, 8, 9, 10]
[1, 2, 33, 4, 5, 66, 7, 8, 99, 10]
[1, 2, 33, 4, 5, 66, 7, 8, 99, 10]
以上就是查询并修改数组中的元素的一些方法,希望对大家有所帮助。