假设我有一个10 * 10的数组x,在Matlab中,我可以使用诸如x(1 : 3 : 7, 2 : 4 :10)
这样的代码来实现跨步访问。我如何在Python中做同样的事情?
谢谢!
发布于 2018-06-15 08:56:32
使用numpy
import numpy as np
simple_array = np.arange(6)
print(simple_array)
# array[startIndex : endIndex : stepValue]*
print(simple_array[1:5:2])
# if you want to include the last value, you need to go above it
print(simple_array[1:6:2])
# obtain the first n-elements using array[:n]. Note that the n-th element isn't included
print(simple_array[:4])
# or the elements after that with array[n:]. Note that the n-th element is included
print(simple_array[4:])
# use step value with array[::n]
print(simple_array[::2])
# this will return the columns 3-5, with 5 not being included
print(simple_array[3:5])
# here we start at column 1, with a step of 2
print(simple_array[1::2])
这将输出:
[0, 1, 2, 3, 4, 5]
[1, 3]
[1, 3, 5]
[0, 1, 2, 3]
[4, 5]
[0, 2, 4]
[3, 4]
[1, 3, 5]
https://stackoverflow.com/questions/50867793
复制相似问题