简体   繁体   English

Pythonic方式获取序列的第一个和最后一个元素

[英]Pythonic way to get the first AND the last element of the sequence

What is the easiest and cleanest way to get the first AND the last elements of a sequence? 获取序列的第一个和最后一个元素的最简单,最简洁的方法是什么? Eg, I have a sequence [1, 2, 3, 4, 5] , and I'd like to get [1, 5] via some kind of slicing magic. 例如,我有一个序列[1, 2, 3, 4, 5] ,我希望通过某种切片魔法获得[1, 5] What I have come up with so far is: 到目前为止我想出的是:

l = len(s)
result = s[0:l:l-1]

I actually need this for a bit more complex task. 我实际上需要这个更复杂的任务。 I have a 3D numpy array, which is cubic (ie is of size NxNxN, where N may vary). 我有一个3D numpy数组,它是立方的(即大小为NxNxN,其中N可能会有所不同)。 I'd like an easy and fast way to get a 2x2x2 array containing the values from the vertices of the source array. 我想要一种简单快捷的方法来获取包含源数组顶点值的2x2x2数组。 The example above is an oversimplified, 1D version of my task. 上面的例子是我的任务的过度简化的1D版本。

用这个:

result = [s[0], s[-1]]

This would give you a list of the first and last element in your sequence: 这将为您提供序列中第一个和最后一个元素的列表

 result = [s[0], s[-1]]

Alternatively, this would give you a tuple 或者,这会给你一个元组

 result = s[0], s[-1]

Since you're using a numpy array, you may want to use fancy indexing: 由于您使用的是numpy数组,因此您可能希望使用花哨的索引:

a = np.arange(27)
indices = [0, -1]
b = a[indices] # array([0, 26])

For the 3d case: 对于3d案例:

vertices = [(0,0,0),(0,0,-1),(0,-1,0),(0,-1,-1),(-1,-1,-1),(-1,-1,0),(-1,0,0),(-1,0,-1)]
indices = list(zip(*vertices))  #Can store this for later use.
a = np.arange(27).reshape((3,3,3)) #dummy array for testing.  Can be any shape size :)
vertex_values = a[indices].reshape((2,2,2))

I first write down all the vertices (although I am willing to bet there is a clever way to do it using itertools which would let you scale this up to N dimensions ...). 我首先写下所有顶点(虽然我愿意打赌,有一种聪明的方法可以使用itertools来实现它,这可以让你将它扩展到N维...)。 The order you specify the vertices is the order they will be in the output array. 指定顶点的顺序是它们在输出数组中的顺序。 Then I "transpose" the list of vertices (using zip ) so that all the x indices are together and all the y indices are together, etc. (that's how numpy likes it). 然后我“转置”顶点列表(使用zip ),以便所有x索引在一起,所有y索引在一起,等等(这就是numpy喜欢它的方式)。 At this point, you can save that index array and use it to index your array whenever you want the corners of your box. 此时,您可以保存该索引数组,并在需要方框的角时使用它来索引数组。 You can easily reshape the result into a 2x2x2 array (although the order I have it is probably not the order you want). 您可以轻松地将结果重新整形为2x2x2阵列(尽管我拥有它的顺序可能不是您想要的顺序)。

With the particular case of a (N,N,N) ndarray X that you mention, would the following work for you? 对于你提到的(N,N,N) ndarray X的特殊情况,下面的工作会对你ndarray吗?

s = slice(0,N,N-1)
X[s,s,s]

Example

>>> N = 3
>>> X = np.arange(N*N*N).reshape(N,N,N)
>>> s = slice(0,N,N-1)
>>> print X[s,s,s]
[[[ 0  2]
  [ 6  8]]
 [[18 20]
  [24 26]]]
>>> from operator import itemgetter
>>> first_and_last = itemgetter(0, -1)
>>> first_and_last([1, 2, 3, 4, 5])
(1, 5)

Why do you want to use a slice? 你为什么要用切片? Getting each element with 获得每个元素

result = [s[0], s[-1]]

is better and more readable. 更好,更可读。

If you really need to use the slice, then your solution is the simplest working one that I can think of. 如果你真的需要使用切片,那么你的解决方案是我能想到的最简单的工作方式。

This also works for the 3D case you've mentioned. 这也适用于您提到的3D案例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Pythonic确定当前元素是否是生成器的第一个或最后一个元素的方法? - Pythonic way of determining if the current element is the first or last element of a generator? 用Pythonic方法获取具有特定名称的第一个XML元素的值 - Pythonic way to get value of first XML element with specific name 获取数组的一部分以及numpy中的第一个元素(以pythonic方式) - Get part of array plus first element in numpy (In a pythonic way) 获取多维numpy数组的第一个元素的pythonic方法 - pythonic way to get first element of multidimensional numpy array 检测“for”循环中最后一个元素的pythonic方法是什么? - What is the pythonic way to detect the last element in a 'for' loop? 用Python方法获取枚举的最后一个索引值 - Pythonic way to get last index value of enumerate 大多数pythonic方式获得前一个元素 - Most pythonic way to get the previous element 是否有一种pythonic方式可以知道for中的第一个和最后一个循环何时通过? - Is there a pythonic way of knowing when the first and last loop in a for is being passed through? 用最恐怖的方式替换第一个和最后一个字符串 - Replace First and Last Word of String in the Most Pythonic Way 进行设置差异时忽略最后一个元素的 Pythonic 方式 - Pythonic way of ignoring the last element when doing set difference
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM