gpt4 book ai didi

python - 如何创建一个空数组并追加它?

转载 作者:行者123 更新时间:2023-12-05 03:52:26 25 4
gpt4 key购买 nike

我是编程新手。我正在尝试运行这段代码

from numpy import *

x = empty((2, 2), int)

x = append(x, array([1, 2]), axis=0)

x = append(x, array([3, 5]), axis=0)

print(x)

但是我得到了这个错误

Traceback (most recent call last):
File "/home/samip/PycharmProjects/MyCode/test.py", line 3, in <module>

x = append(x, array([1, 2]), axis=0)

File "<__array_function__ internals>", line 5, in append

File "/usr/lib/python3/dist-packages/numpy/lib/function_base.py", line 4700, in append

return concatenate((arr, values), axis=axis)

File "<__array_function__ internals>", line 5, in concatenate

ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)

最佳答案

您可以通过[] 创建空列表。要添加新项目,请使用 append。要添加其他列表,请使用 extend

x = [1, 2, 3]
x.append(4)
x.extend([5, 6])

print(x)
# [1, 2, 3, 4, 5, 6]

关于python - 如何创建一个空数组并追加它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62199244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com