假设我在python中有以下列表:
x = [1,2,3,4,5,6,7,8,9,10]我想将值0赋给列表中的特定位置,例如位置0、7和9。在python中,我可以在不使用循环的情况下执行以下操作吗?
x[0,7,9] = 0发布于 2013-05-31 05:32:22
这就对了:
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是一个稍微高级一点的东西。
https://stackoverflow.com/questions/16846201
复制相似问题