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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:23:36  来源:igfitidea点击:

How to set first N elements of array to zero?

pythonarraysnumpy

提问by user3059201

I have a long array:

我有一个长数组:

x= ([2, 5, 4, 7, ...])

for which I need to set the first Nelements 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 numpyfunction?

有没有一种简单的方法可以在 Python 中做到这一点?一些numpy功能?

采纳答案by syntonym

Pure python:

纯蟒蛇:

x[:n] = [0] * n

with numpy:

与麻木:

y = numpy.array(x)
y[:n] = 0

also note that x[:n] = 0does notwork if xis 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}] * nfor 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