【问题标题】:Default value for out-of-bounds list index [duplicate]越界列表索引的默认值 [重复]
【发布时间】:2013-07-18 11:07:42
【问题描述】:

是否有标准方法从列表中获取项目但返回默认值超出范围?

作为一个例子,我现在有一个这样的函数(嗯,这个函数有很多变种,我最新的是用于读取 CSV 文件):

def list_get_def( lst, ndx, def_val ):
  if ndx >= len(lst):
    return def_val
  return lst[ndx]

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    使用try-except 块并捕获IndexError。

    >>> def testFunc(lst, index):
            try:
                return lst[index]
            except IndexError:
                return "abc"
    
    
    >>> testFunc([1, 2, 3], 2)
    3
    >>> testFunc([1, 2, 3], 9)
    'abc'
    

    一个类似的问题here 讨论了为什么列表没有像字典那样的get 方法。

    如果您确实想使用if 语句,只需一行代码即可。

    >>> def testFunc(lst, index):
            return lst[index] if index < len(lst) else "abc"
    
    >>> testFunc([1, 2, 3], 2)
    3
    >>> testFunc([1, 2, 3], 9)
    'abc'
    

    【讨论】:

    • 那比只检查长度要长。
    • 是的。但是,这是做你想做的事的标准方式。
    • 如果你不太可能越界,它也会更快。
    【解决方案2】:

    如果你不想覆盖列表的 getimtem,你可以编写一个 get 方法,比如 dict 有:

    class fancyList_if(list):
        def get(self, index, default = None):
            if (index > len(self)):
                return default
            return self.__getitem__(index)
    

    如果您很少期望超出范围,那么您可以将其实现为异常

    class fancyList_except(list):
        def get(self, index, default = None):
            try:
                self.__getitem__(index)
            except IndexError:
                return default
    

    基准测试:

    In [58]: a = fancyList_if((1,3,4,5))
    
    In [59]: b = fancyList_except((1,3,4,5))
    
    In [60]: %timeit a.get(2, 10)
    1000000 loops, best of 3: 494 ns per loop
    
    In [61]: %timeit a.get(10, 10)
    1000000 loops, best of 3: 305 ns per loop
    
    In [62]: %timeit b.get(2, 10)
    1000000 loops, best of 3: 409 ns per loop
    
    In [63]: %timeit b.get(10, 10)
    1000000 loops, best of 3: 1.67 us per loop
    

    收支平衡:

    500hit + 300miss = 400hit + 1700miss

    命中/未命中 = 14

    因此,如果您预计超过 1/14 的查找“失败”,则使用 if 语句,否则使用 try/catch。

    【讨论】:

    • 我真的不想改变现有函数的行为,因为那样会引起混乱。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多