1. 使用列表推导式:
original_list = [1, 2, 3, 4, 5]new_element = 99index_to_replace = 2original_list[index_to_replace] = new_elementprint(original_list) 输出:[1, 2, 99, 4, 5]
original_list = [1, 2, 3, 4, 5]new_element = 99index_to_replace = 2for i, value in enumerate(original_list):if i == index_to_replace:original_list[i] = new_elementprint(original_list) 输出:[1, 2, 99, 4, 5]
3. 使用`numpy`库:

import numpy as npa = np.arange(9).reshape((3, 3))a[a == 4] = 1print(a) 输出:[[0 1 2][3 1 5][6 7 8]]
4. 使用`numpy.where`函数:
import numpy as npa = np.arange(9).reshape((3, 3))a[np.where(a == 0)] = 1print(a) 输出:[[1 1 2][3 4 5][6 7 8]]
5. 使用`replace`函数(适用于`numpy`数组):
import numpy as npa = np.array([-np.inf, -2, 3, 4, 5])a = a.replace(float("-inf"), 0)print(a) 输出:[0. -2. 3. 4. 5.]
以上是几种在Python中替换数组元素的方法。请根据你的具体需求选择合适的方法
