简体   繁体   English

IndexError:预期范围为[1,3)的暗淡0索引Python错误

[英]IndexError: expected dim 0 index in range [1, 3) Error Python

In Python, I am having strange error, where a = [x[1], x[2]] works, but a = x[1:] does not. 在Python中,我遇到一个奇怪的错误,其中a = [x[1], x[2]]有效,但是a = x[1:]无效。

>>> out                                                                    
farray([Y[0], Y[1], Y[2]])                                                        
>>> out[1]
Y[1]
>>> remaining_out = [out[1], out[2]]
>>> remaining_out[0]
Y[1]
>>> remaining_out = out[1:]
>>> remaining_out[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module> 
File "/home/kmshah4/.local/lib/python3.6/site-packages/pyeda/boolalg/bfarray.py", line 485, in __getitem__
nsls = self._norm_slices(fsls)                                                                                                                                        File "/home/kmshah4/.local/lib/python3.6/site-packages/pyeda/boolalg/bfarray.py", line 890, in _norm_slices                             nsls.append(_norm_index(i, fsl, *self.shape[i]))
File "/home/kmshah4/.local/lib/python3.6/site-packages/pyeda/boolalg/bfarray.py", line 1127, in _norm_index
raise IndexError(fstr.format(dim, start, stop))
IndexError: expected dim 0 index in range [1, 3)

Please help. 请帮忙。

Objects in Python do not automatically support slice notation just because they support indexing. Python中的对象不仅仅因为它们支持索引就自动支持切片符号。 That has to be programmed in. There may be syntax more convenient than what you're using though. 必须对此进行编程。不过,语法可能比您正在使用的语法更方便。

If it's iterable, you can convert to a list first, and then slice it, like 如果是可迭代的,则可以先转换为列表,然后将其切片,例如

a = [*x][1:]

For especially large iterables (does not seem to be the case here), this may be inefficient. 对于特别大的可迭代对象(这里似乎不是这种情况),这可能效率不高。 In that case, islice it before you unpack into the list. 在这种情况下, islice对它进行 islice然后再解压缩到列表中。

from itertools import islice
a = [*islice(x, 1, None)]

But objects do not automatically support iteration just because they support indexing either. 但是对象不仅仅因为它们支持索引就自动支持迭代。 If that's the case, you can still iterate manually with range() and a comprehension, 如果是这种情况,您仍然可以使用range()和理解力手动进行迭代,

a = [x[i] for i in range(1, len(x))]

Though this isn't really shorter until you have a few more elements to deal with. 尽管实际上还没有缩短,直到您还有更多要处理的元素。 If you need this pattern a lot you could abstract it into a function. 如果您非常需要此模式,则可以将其抽象为一个函数。

And finally, objects do not necessarily support len just because they support indexing. 最后,对象不一定仅因为支持索引而支持len If you don't know the length in advance, about all you can do is loop through and catch the LookupError at that point. 如果您事先不知道长度,那么您可以做的就是循环遍历并在LookupError捕获LookupError

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM