python - 使用多维数组中的每个第一个元素

标签 python arrays list multidimensional-array slice

我原以为,如果您运行 print mdarray[::][1],您将打印数组中每个元素的第一个子元素。我哪里做错了?

对于 p.plot(x,y[::][1]) 我特别需要它,我绝对想使用 for 循环,因为它非常慢,除非我把事情弄糊涂了。

我哪里错了?谢谢!

编辑

我仍然不知道我从哪里得到 [::] 东西,但我用其中任何一个解决了我的问题

p.plot(x,c[:,1],color='g',label="收盘价")

p.plot(x,[i[1] for i in c],color='g',label="Closing value")

似乎没有任何明显的时间差异,所以我想我会使用第二个,因为它对我来说看起来更 pythonic/可读。还是我遗漏了什么?

感谢大家的帮助!

最佳答案

如果 mdarray 是一个 numpy 数组,您可以使用 mdarray[:,0] 访问它的第一列

In [8]: mdarray = np.array([[1, 2, 4], [4, 5, 6], [7, 8, 9]])

In [9]: mdarray
Out[9]:
array([[1, 2, 4],
       [4, 5, 6],
       [7, 8, 9]])

In [10]: mdarray[:,0]
Out[10]: array([1, 4, 7])

UPD

快速而肮脏的测试

In [28]: mdarray = np.zeros((10000,10000))

In [29]: %timeit -n1000 [x[0] for x in mdarray]
1000 loops, best of 3: 2.7 ms per loop

In [30]: %timeit -n1000 mdarray[:,0]
1000 loops, best of 3: 567 ns per loop

关于python - 使用多维数组中的每个第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29934201/

相关文章:

python - Python 中的重定向打印 : val = print(arg) to output mixed iterable to file

python - 值错误: expected 2D or 3D input (got 1D input) PyTorch

python - 使用opecv2和Python显示图像时滞后

c - 通过引用传递字符串数组以在 C 中运行和修改内容

javascript - 遍历数组以使用 d3 追加圆圈

python - 创建一个以列表为值的字典,并对列表内的元素进行排序

c# - 将 List<int> 作为查询参数传递给 SQL Server

python - 从 CSV 文件构建列表列表

C程序计算NxN矩阵的行列式

python - 在Python中,如何设计复杂的列表理解的样式