I want to get all but the first and last n elements from an array, can I do this while keeping consistent behaviour for n=0 without using an if statement? (Python 2.7). This does what I want, but falls apart if nCut=0:
我想从数组中得到除了第一个和最后一个n个元素之外的所有元素,我能在不使用if语句的情况下保持n=0的一致行为吗?(Python 2.7)。这就是我想要的,但是如果nCut=0,就会崩溃:
nCut = 3
newArray = oldArray[nCut:-nCut]
This is closer, but doesn't include the last element (and is also really just a slightly hidden if statement)
这更接近了,但不包含最后一个元素(实际上也是一个稍微隐藏的if语句)
newArray = oldArray[nCut:-nCut-1*(nCut<1)]
I have to do this to a bunch of arrays I'm loading from files, so not having a big ugly doubled up if
for the n=0 case would be nice.
我必须对我从文件中加载的一堆数组做这样的处理,所以如果n=0的情况下,不会有一个很糟糕的双数组。
1 个解决方案
#1
5
Add len(oldArray)
yourself instead of counting on the slicing implementation to do it for you:
添加len(oldArray)自己,而不是依靠切片实现为您做:
newArray = oldArray[nCut:len(oldArray)-nCut]
#1
5
Add len(oldArray)
yourself instead of counting on the slicing implementation to do it for you:
添加len(oldArray)自己,而不是依靠切片实现为您做:
newArray = oldArray[nCut:len(oldArray)-nCut]