Python中的第一个和最后一个元素

pis*_*tal 37 python arrays numpy

我试图动态地从数组中获取第一个和最后一个元素.

所以,让我们假设数组有6个元素.

test = [1,23,4,6,7,8]
Run Code Online (Sandbox Code Playgroud)

如果我想要获得first and last = 1,8,23,74,6.有没有办法按此顺序获取元素?我看了几个Link Link2的问题.我接受了这些链接的帮助,我想出了这个原型..

#!/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]]]
Run Code Online (Sandbox Code Playgroud)

但是如果你有超过6个元素,这个原型将无法扩展.所以,我想知道是否有办法动态获取这对元素.

谢谢!

len*_*ooh 119

我结束了这里,因为我搜索了"python的第一个和最后一个数组元素",除此之外发现了其他所有内容.所以这是标题问题的答案:

a = [1,2,3]
a[0] # first element (returns 1)
a[-1] # last element (returns 3)
Run Code Online (Sandbox Code Playgroud)

  • Bravo简洁和遵循指示. (2认同)

NPE*_*NPE 24

怎么样:

In [10]: arr = numpy.array([1,23,4,6,7,8])

In [11]: [(arr[i], arr[-i-1]) for i in range(len(arr) // 2)]
Out[11]: [(1, 8), (23, 7), (4, 6)]
Run Code Online (Sandbox Code Playgroud)

根据大小arr,在NumPy中写入整个内容可能会更高效:

In [41]: arr = numpy.array([1,23,4,6,7,8]*100)

In [42]: %timeit [(arr[i], arr[-i-1]) for i in range(len(arr) // 2)]
10000 loops, best of 3: 167 us per loop

In [43]: %timeit numpy.vstack((arr, arr[::-1]))[:,:len(arr)//2]
100000 loops, best of 3: 16.4 us per loop
Run Code Online (Sandbox Code Playgroud)


Pej*_*vak 11

arr = np.array([1,2,3,4])
arr[-1] # last element
Run Code Online (Sandbox Code Playgroud)


Fre*_*Foo 5

使用 Numpy 的奇特索引:

>>> test
array([ 1, 23,  4,  6,  7,  8])

>>> test[::-1]  # test, reversed
array([ 8,  7,  6,  4, 23,  1])

>>> numpy.vstack([test, test[::-1]])  # stack test and its reverse
array([[ 1, 23,  4,  6,  7,  8],
       [ 8,  7,  6,  4, 23,  1]])

>>> # transpose, then take the first half;
>>> # +1 to cater to odd-length arrays
>>> numpy.vstack([test, test[::-1]]).T[:(len(test) + 1) // 2]
array([[ 1,  8],
       [23,  7],
       [ 4,  6]])
Run Code Online (Sandbox Code Playgroud)

vstack复制数组,但所有其他操作都是恒定时间指针技巧(包括反转),因此非常快。