数组中的python第一个和最后一个元素

Python first and last element from array

我正在尝试从数组中动态获取第一个和最后一个元素。

所以,假设数组有6个元素。

1
test = [1,23,4,6,7,8]

如果我想得到first and last = 1,823,74,6。有没有办法按此顺序获取元素?我看了一些链接链接2的问题。我得到了这些链接的帮助,我想出了这个原型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python

import numpy

test = [1,23,4,6,7,8]
test1 = numpy.array([1,23,4,6,7,8])
len_test = len(test)
first_list = [0,1,2]
len_first = len(first_list)
second_list = [-1,-2,-3]
len_second = len(second_list)

for a in range(len_first):
        print numpy.array(test)[[first_list[a] , second_list[a]]]
        print test1[[first_list[a], second_list[a]]]

但如果你有6个以上的元素,这个原型就无法缩放。所以,我想知道是否有办法动态地得到这对元素。

谢谢!


(P)I ended here,because I googled for"python first and last element of array",and found everything else but this.So here's the answer to the title question:(p)字母名称


(P)How about:(p)字母名称(P)取决于多种元素0的六个字母,在数字上写下实体的想法可能更为实际:(p)字母名称


(P)Using numpy's fancy indexing:(p)字母名称(P)EDOCX1 3 original copies the array,but all the other operations are constant-time pointer tricks(including reversal)and hence are very fast.(p)


字母名称(P)其他选项(p)字母名称


(P)这个怎么样?(p)字母名称(P)The EDOCX1 original 1 ensures that the middle element of ODD length arrays is also returned:(p)字母名称(P)只要使用EDOCX1个音符2个音符就会把千年发展目标的中数列出来(p)


(P)This does it.Note that with an ODD number of elements the one in the middle won't be included.(p)字母名称(P)Output:(p)字母名称


(P)Assuming the list has a even number of elements,you could do:(p)字母名称