向lis添加起始索引

2024-05-08 03:02:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个numpy阵列

a = [1 2 3]

我想添加0作为列表的第一个索引。我该怎么做?你知道吗

输出:

a = [0 1 2 3]

Tags: numpy列表
2条回答

使用^{}

>>> a = [1, 2, 3]
>>> a.insert(0, 0)
>>> a
[0, 1, 2, 3]

使用切片分配:

>>> a = [1, 2, 3]
>>> a[:0] = [0]
>>> a
[0, 1, 2, 3]

根据标签更改更新。你知道吗

使用^{}

>>> a = np.array([1, 2, 3])
>>> np.insert(a, 0, 0)
array([0, 1, 2, 3])

^{}

>>> np.hstack([[0], a])
array([0, 1, 2, 3])

你可以用列表.插入(参考:http://docs.python.org/2/tutorial/datastructures.html

列表.插入(i,x) 在给定位置插入项目。第一个参数是要插入的元素的索引,因此a.insert(0,x)在列表的前面插入,而a.insert(len(a),x)等价于a.append(x)。你知道吗

a.insert(0,0) 

相关问题 更多 >