代码之家  ›  专栏  ›  技术社区  ›  MichaelR

索引位置未知时切片与索引的区别

  •  0
  • MichaelR  · 技术社区  · 7 年前

    当索引位置未知时,使用索引而不是索引作为索引返回范围误差更好吗?

    from random import randint
    
    __index__ = randint(0, 100)
    print(__index__)
    
    key = "Some random string which comes on our way and we don't find the length"
    
    ''' Slicing is better when unknown length of a string?''' 
    x = key[__index__:__index__+1]
    if x is '':
        print("No value in slicing")
    else:
        print("Sliced value %s" % (x))
    
    ''' Indexing runs into IndexError: string index out of range when out of range'''
    x = key[__index__]
    if x is None:
        print("No value in indexing")
    else:
        print("Indexed value %s" % (x))
    

    当随机索引超出范围时,它会在索引中出错。在这种情况下使用切片更好吗?

    $ python main.py
    98
    No value in slicing
    Traceback (most recent call last):
      File "main.py", line 15, in <module>
        x = key[__index__]
    IndexError: string index out of range
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   shahbazkhan    7 年前

    试试看:

    from random import randint
    
    index = randint(0, 100)
    
    key = "Some random string which comes on our way and we don't find the length"
    
    try:
        print('Index value: {}'.format(key[index]))
    except IndexError:
        print('No value found with index: {}'.format(index))
    

    在你的代码中, key[__index__:__index__+1] key[__index__] IndexError 如果找不到索引,而如果找不到切片,切片将返回空字符串(或元组或列表等)。无论如何,最好处理引发异常的情况,此时,您就知道没有找到索引。这样也可以避免不必要的 if else

    我希望这有帮助!

        2
  •  0
  •   Somya Avasthi    7 年前

    当索引位置未知时,它最好使用切片而不是索引。因为,如果尝试检索超出对象范围的值,则按索引获取值可能会引发索引器错误,同时如果使用切片运算符,则即使尝试检索超出范围的值,也不会引发任何类型的错误。切片只会为未找到的任何索引返回空对象。

    >>>l=[1,2,3,4,5,5]
    >>>l[6:]
    >>>[]
    

    对于同一个例子,如果我们做索引,就会引发错误。

    >>>l[6]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IndexError: list index out of range