Python 如何将数组的前 N 个元素设置为零?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31049544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set first N elements of array to zero?
提问by user3059201
I have a long array:
我有一个长数组:
x= ([2, 5, 4, 7, ...])
for which I need to set the first N
elements to 0
. So for N = 2
, the desired output would be:
为此,我需要将第一个N
元素设置为0
. 因此,对于N = 2
,所需的输出将是:
x = ([0, 0, 4, 7, ...])
Is there an easy way to do this in Python? Some numpy
function?
有没有一种简单的方法可以在 Python 中做到这一点?一些numpy
功能?
采纳答案by syntonym
Pure python:
纯蟒蛇:
x[:n] = [0] * n
with numpy:
与麻木:
y = numpy.array(x)
y[:n] = 0
also note that x[:n] = 0
does notwork if x
is a python list (instead of a numpy array).
还注意到,x[:n] = 0
确实没有,如果工作x
是一个Python列表(而不是numpy的阵列)。
It is also a bad idea to use [{some object here}] * n
for anything mutable, because the list will not contain n different objects but n references to the same object:
[{some object here}] * n
用于任何可变对象也是一个坏主意,因为列表将不包含 n 个不同的对象,而是 n 个对同一对象的引用:
>>> a = [[],[],[],[]]
>>> a[0:2] = [["a"]] * 2
>>> a
[['a'], ['a'], [], []]
>>> a[0].append("b")
>>> a
[['a', 'b'], ['a', 'b'], [], []]
回答by jhoepken
Just set them explicitly:
只需明确设置它们:
x[0:2] = 0