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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14609720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:57:51  来源:igfitidea点击:

NumPy first and last element from array

pythonarraysnumpy

提问by pistal

I am trying to dynamically get the first and last element from an array.

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

So, let us suppose the array has 6 elements.

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

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

If I am trying to get the first and last = 1,8, 23,7and 4,6. Is there a way to get elements in this order? I looked at a couple of questions LinkLink2. I took help of these links and I came up with this prototype..

如果我试图获取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]]]

But this prototype won't scale for if you have more than 6 elements. So, I was wondering if there is way to dynamically get the pair of elements.

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

Thanks!

谢谢!

采纳答案by NPE

How about:

怎么样:

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)]

Depending on the size of arr, writing the entire thing in NumPy may be more performant:

根据 的大小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

回答by Abhijit

>>> test = [1,23,4,6,7,8]
>>> from itertools import izip_longest
>>> for e in izip_longest(test, reversed(test)):
    print e


(1, 8)
(23, 7)
(4, 6)
(6, 4)
(7, 23)
(8, 1)

Another option

另外一个选项

>>> test = [1,23,4,6,7,8]
>>> start, end = iter(test), reversed(test)
>>> try:
    while True:
        print map(next, [start, end])
except StopIteration:
    pass

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

回答by isedev

How about this?

这个怎么样?

>>> import numpy
>>> test1 = numpy.array([1,23,4,6,7,8])
>>> forward = iter(test1)
>>> backward = reversed(test1)
>>> for a in range((len(test1)+1)//2):
...     print forward.next(), backward.next()
... 
1 8
23 7
4 6

The (len(test1)+1)//2ensures that the middle element of odd length arrays is also returned:

(len(test1)+1)//2确保了奇数长度阵列的中间元件也被返回:

>>> test1 = numpy.array([1,23,4,9,6,7,8]) # additional element '9' in the middle
>>> forward = iter(test1)                                                      
>>> backward = reversed(test1)
>>> for a in range((len(test1)+1)//2):
...     print forward.next(), backward.next()
1 8
23 7
4 6
9 9

Using just len(test1)//2will drop the middle elemen of odd length arrays.

使用 justlen(test1)//2将删除奇数长度数组的中间元素。

回答by Rui Vieira

Assuming the list has a even number of elements, you could do:

假设列表有偶数个元素,你可以这样做:

test = [1,23,4,6,7,8]
test_rest = reversed(test[:len(test)/2])

for n in len(test_rest):
    print [test[n], test_test[n]]

回答by ford

This does it. Note that with an odd number of elements the one in the middle won't be included.

这样做。请注意,对于奇数个元素,将不包括中间的元素。

test = [1, 23, 4, 6, 7, 8, 5]    
for i in range(len(test)/2):
    print (test[i], test[-1-i])

Output:

输出:

(1, 5)
(23, 8)
(4, 7)

回答by Fred Foo

Using Numpy's fancy indexing:

使用 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]])

vstackcopies the array, but all the other operations are constant-time pointer tricks (including reversal) and hence are very fast.

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

回答by lenooh

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:

我到此结束,因为我在 google 上搜索了“python 数组的第一个和最后一个元素”,并找到了除此之外的所有其他内容。所以这是标题问题的答案:

a = [1,2,3]
a[0] # first element (returns 1)
a[-1] # last element (returns 3)

回答by ozcanyarimdunya

You can simply use takemethod and index of element (Last index can be -1).

您可以简单地使用take元素的方法和索引(最后一个索引可以是-1)。

arr = np.array([1,2,3])

last = arr.take(-1)
# 3

回答by Mehdi_Pejvak

arr = np.array([1,2,3,4])
arr[-1] # last element