[英]Array Prints like List but its a single integer in variable explorer? Why?
当我打印出下面的代码 Q 时,打印出来的代码就像是 (3 5 7 9) 与下一个数字的总和。 但在变量资源管理器中,它是一个 integer 我想将结果 Q 作为一个数组
Q = [3, 5, 7, 9]
import numpy as np
A = [1, 2, 3, 4, 5]
for i in range(0,4):
Q = np.array(A[i]+A[i+1])
print(Q)
for i in range(0,4):
Q = []
Q.append(Q[i] + A[i]+A[i+1])
print(Q)
这也行不通
目前您只是每次都重新声明Q
并且它从未添加到某些值集合中
相反,从一个空列表(或者在你的情况下可能是一个 numpy 数组)开始,在你的循环之外和append在每个循环周期中给它的值
Q
是一个 numpy 阵列,但这不是您所期望的!
它没有维度,只引用一个值
>>> type(Q)
<class 'numpy.ndarray'>
>>> print(repr(Q))
array(9)
>>> import numpy as np
>>> A = [1, 2, 3, 4, 5]
>>> Q = np.array([], dtype=np.uint8)
>>> for i in range(4):
... Q = np.append(Q, A[i]+A[i+1]) # reassign each time for np
...
>>> print(Q)
[3 5 7 9]
Note that numpy arrays should be reassigned via np.append , while a normal python list has a .append()
method (which does not return the list, but directly appends to it)
>>> l = ['a', 'b', 'c'] # start with a list of values
>>> l.append('d') # use the append method
>>> l # display resulting list
['a', 'b', 'c', 'd']
如果您没有被迫使用 numpy 数组开始,这可以通过列表理解来完成
之后也可以将结果列表制成 numpy 数组
>>> [(x + x + 1) for x in range(1, 5)]
[3, 5, 7, 9]
连同简化的数学
>>> np.array([x*2+3 for x in range(4)])
array([3, 5, 7, 9])
如果要使用 Numpy,请使用 Numpy 。 从 Numpy 数组(一维,包含值)开始,如下所示:
A = np.array([1, 2, 3, 4, 5])
(是的,你从列表中初始化它)。
或者您可以使用 Numpy 的内置工具创建这种模式数据:
A = np.arange(1, 6) # it works similarly to the built-in `range` type,
# but it does create an actual array.
现在我们可以得到要在加法的左侧和右侧使用的值:
# You can slice one-dimensional Numpy arrays just like you would lists.
# With more dimensions, you can slice in each dimension.
X = A[:-1]
Y = A[1:]
并将这些值按元素相加:
Q = X + Y # yes, really that simple!
最后一行是您使用 Numpy 解决此类问题的原因。 否则,只需使用列表推导:
A = list(range(1, 6)) # same as [1, 2, 3, 4, 5]
# Same slicing, but now we have to do more work for the addition,
# by explaining the process of pairing up the elements.
Q = [x + y for x, y in zip(A[:-1], A[1:])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.