如何将数组的前N个元素设置为零? [英] How to set first N elements of array to zero?

查看:87
本文介绍了如何将数组的前N个元素设置为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数组很长:

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

我需要将

的第一个N元素设置为0.因此,对于N = 2,所需的输出将是:

for which I need to set the first N elements to 0. So for N = 2, the desired output would be:

x = ([0, 0, 4, 7, ...])

在Python中有一种简单的方法吗?一些numpy功能?

Is there an easy way to do this in Python? Some numpy function?

推荐答案

纯python:

x[:n] = [0] * n

和numpy:

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

还请注意,如果x是python列表(而不是numpy数组),则x[:n] = 0不会不起作用.

also note that x[:n] = 0 does not work if x is a python list (instead of a numpy array).

对任何可变的东西使用[{some object here}] * n也是一个坏主意,因为列表将不包含n个不同的对象,而是n个对同一对象的引用:

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:

>>> a = [[],[],[],[]]
>>> a[0:2] = [["a"]] * 2
>>> a
[['a'], ['a'], [], []]
>>> a[0].append("b")
>>> a
[['a', 'b'], ['a', 'b'], [], []]

这篇关于如何将数组的前N个元素设置为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆