在Python中替换数组中的素,你可以使用以下几种方法:
1. 使用列表推导式:
```python
original_list = [1, 2, 3, 4, 5]
new_element = 99
index_to_replace = 2
original_list[index_to_replace] = new_element
print(original_list) 输出:[1, 2, 99, 4, 5]
2. 使用`enumerate`函数和循环遍历列表:```pythonoriginal_list = [1, 2, 3, 4, 5]
new_element = 99
index_to_replace = 2
for i, value in enumerate(original_list):
if i == index_to_replace:
original_list[i] = new_element
print(original_list) 输出:[1, 2, 99, 4, 5]
3. 使用`numpy`库:
```python
import numpy as np
a = np.arange(9).reshape((3, 3))
a[a == 4] = 1
print(a) 输出:
[[0 1 2]
[3 1 5]
[6 7 8]]
4. 使用`numpy.where`函数:```pythonimport numpy as np
a = np.arange(9).reshape((3, 3))
a[np.where(a == 0)] = 1
print(a) 输出:
[[1 1 2]
[3 4 5]
[6 7 8]]
5. 使用`replace`函数(适用于`numpy`数组):
```python
import numpy as np
a = np.array([-np.inf, -2, 3, 4, 5])
a = a.replace(float("-inf"), 0)
print(a) 输出:
[0. -2. 3. 4. 5.]
以上是几种在Python中替换数组素的方法。请根据你的具体需求选择合适的方法
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/78190.html