Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 获取导致索引器异常的索引_Python_Python 2.7 - Fatal编程技术网

Python 获取导致索引器异常的索引

Python 获取导致索引器异常的索引,python,python-2.7,Python,Python 2.7,是否可以获取导致索引器异常的索引 示例代码: arr = [0, 2, 3, 4, 5, 6, 6] try: print arr[10] # This will cause IndexError except IndexError as e: print e.args # Can I get which index (in this case 10) caused the exception? 除了手动跟踪您访问的索引之外,我不这么认为,至少在2.7中是这样。除非我误读了提

是否可以获取导致
索引器异常的索引

示例代码:

arr = [0, 2, 3, 4, 5, 6, 6]
try:  
   print arr[10] # This will cause IndexError
except IndexError as e:
    print e.args # Can I get which index (in this case 10) caused the exception?

除了手动跟踪您访问的索引之外,我不这么认为,至少在2.7中是这样。除非我误读了提案,否则只能手动执行;例如:

arr = [1,2,3]
try:
    try_index = 42
    print(arr[try_index])
except IndexError:
    print 'Index', try_index, 'caused an IndexError'

没有直接的方法,因为与
KeyError
不同,
indexer
尚未提供此信息。您可以对内置的
列表
进行子类化,以使用所需的参数生成
索引器

class vist(list): # Verbose list
    def __getitem__(self, item):
        try:
            v = super().__getitem__(item) # Preserve default behavior
        except IndexError as e:
            raise IndexError(item, *e.args) # Construct IndexError with arguments

        return v

arr = [0, 2, 3, 4, 5, 6, 6] # list
arr = vist(arr) # vist

try:
    arr[10]
except IndexError as e:
    print(e.args) # (10, 'list index out of range')

实际上,您甚至不需要将其转换回正常的
列表

,您可以手动检查列表的长度,因为此时会导致第一个索引器。@sagarchalise,true,但它是!我想这是最简单的,尽管当你访问一个列表的20个预先确定的索引时,这不会有用,在这种情况下,你需要在每次访问索引之前更新try_索引。与打印arr[0]相同;打印arr[21];print arr[15]etcWell在这种情况下,您始终可以编写一个处理异常的函数,以便只需执行
my_print(arr,0);我的打印(arr,21);我的打印(arr,15)
只是想知道,
IndexError
是否在Python3中提供了这些信息,或者它仍然没有提供这些信息?