假设我在 python 中有以下列表:
x = [1,2,3,4,5,6,7,8,9,10]
我想将值 0 分配给列表中的特定位置,例如位置 0、7 和 9。我可以在 python 中执行类似以下操作而不使用循环吗?
x[0,7,9] = 0
请您参考如下方法:
你去吧:
x[0] = x[7] = x[9] = 0
您也可以使用 numpy 来做到这一点以更通用和灵活的方式排列数组:
>>> import numpy as np
>>> x = np.array([1,2,3,4,5,6,7,8,9,10])
>>> indices = [0,7,9]
>>> x[indices] = 0 # or just x[[0,7,9]] = 0
>>> x
array([0, 2, 3, 4, 5, 6, 7, 0, 9, 0])
但这可能不是您要找的东西,因为 numpy 是一种稍微高级一些的东西。
