为什么Python 3 itertools.chain不让我实现多范围

问题描述 投票:0回答:1

我正在尝试使用itertools.chain来实现multirange的概念,相当于串联的多个范围:

a = np.array( range( 37 ) )
print("a", a, file = sys.stderr)
c = chain(range(0,13), range(23,29 ) )
print( "list(c)", list(c), file = sys.stderr )

到目前为止,很好。接下来,我想使用c作为复合数组索引,类似于我可以说的

a[ range(2,8) ]  =>  array( [2, 3, 4, 5, 6, 7 ] )

所以,去了:

x = a[ c ]
print( "x", x, file = sys.stderr )

但是...

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-8-192fff14b87d> in <module>
      3 c = chain(range(0,13), range(23,29 ) )
      4 print( "list(c)", list(c), file = sys.stderr )
----> 5 x = a[c]
      6 print( "x", x, file = sys.stderr )

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

显然,这是另一个Python索引之谜。有人可以告诉我我在做什么错,并帮助我弄清楚如何获得我的意图(“多范围”)。我知道我可以只使用list(c)进行索引,但是我认为这消除了我的意图的另一部分,即延迟枚举隐含的索引集。

python-3.x numpy itertools
1个回答
0
投票

正如错误所说,只有有效的索引是integersslicesellipsis这里c<class 'itertools.chain'>]的实例

您可以做的是将其转换为列表,然后使用它。

>>> c = chain(range(0,13), range(23,29 ) )
>>> a[list(c)]
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 23, 24, 25, 26,
       27, 28])
© www.soinside.com 2019 - 2024. All rights reserved.