选择数组的每n个索引

时间:2017-10-09 18:29:56

标签: python arrays numpy

如果我有一个长度为100个元素的数组,那么获得每个n个索引的Pythonic方法最多。例如,如果我想要一个数组a的每5个索引,我怎么能得到一个数组b=[[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14],...],其中b的每个元素是每5个索引的一个子数组? / p>

3 个答案:

答案 0 :(得分:5)

您只想reshape您的数组:

>>> arr = np.arange(100)
>>> arr
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
       34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
       51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67,
       68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
       85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99])
>>> arr.reshape(-1, 5)
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24],
       [25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34],
       [35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44],
       [45, 46, 47, 48, 49],
       [50, 51, 52, 53, 54],
       [55, 56, 57, 58, 59],
       [60, 61, 62, 63, 64],
       [65, 66, 67, 68, 69],
       [70, 71, 72, 73, 74],
       [75, 76, 77, 78, 79],
       [80, 81, 82, 83, 84],
       [85, 86, 87, 88, 89],
       [90, 91, 92, 93, 94],
       [95, 96, 97, 98, 99]])

注意,我在第一个轴上使用了-1numpy足够智能“解决方程式”,只要您明确地给出其他每个轴。当然,你可以完全明确地完成这个任务:

>>> arr.reshape(20, 5)
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24],
       [25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34],
       [35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44],
       [45, 46, 47, 48, 49],
       [50, 51, 52, 53, 54],
       [55, 56, 57, 58, 59],
       [60, 61, 62, 63, 64],
       [65, 66, 67, 68, 69],
       [70, 71, 72, 73, 74],
       [75, 76, 77, 78, 79],
       [80, 81, 82, 83, 84],
       [85, 86, 87, 88, 89],
       [90, 91, 92, 93, 94],
       [95, 96, 97, 98, 99]])

答案 1 :(得分:1)

<强>更新

如果您正在使用列表,这是一种非常pythonic的方法:

size = 5 # the number of elements of each sublists
l = list(range(100))
result = [l[step:step + size] for step in range(0, len(l), size)]

<强>输出继电器:

[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9],
 [10, 11, 12, 13, 14], [15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24], [25, 26, 27, 28, 29],
 [30, 31, 32, 33, 34], [35, 36, 37, 38, 39],
 [40, 41, 42, 43, 44], [45, 46, 47, 48, 49],
 [50, 51, 52, 53, 54], [55, 56, 57, 58, 59],
 [60, 61, 62, 63, 64], [65, 66, 67, 68, 69],
 [70, 71, 72, 73, 74], [75, 76, 77, 78, 79],
 [80, 81, 82, 83, 84], [85, 86, 87, 88, 89],
 [90, 91, 92, 93, 94], [95, 96, 97, 98, 99]]

答案 2 :(得分:0)

{{1}}

似乎是一种自然而然的方法。