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

在python中,使用默认值创建列表[0]的最佳方法是什么?

  •  0
  • Natim  · 技术社区  · 14 年前

    我正在寻找Python中的函数列表。

    abcd = [1, 2, 3, 4]
    try:
        item = list[5]
    except:
        item = 0
    

    我怎样才能让它看起来像:

    item = abcd.get(5, 0)
    

    2 回复  |  直到 14 年前
        1
  •  3
  •   Alex Martelli    14 年前

    您不能添加 get 方法 list 类,但您可以使用函数:

    def get(alist, index, default):
      try: return alist[index]
      except IndexError: return default
    

    下面是用法示例:

    abcd = [1, 2, 3, 4]
    item = get(abcd, 5, 0)
    

    或者是 列表 :

    class mylist(list):
      def get(self, index, default):
        try: return self[index]
        except IndexError: return default
    

    下面是用法示例:

    abcd = mylist([1, 2, 3, 4])
    item = abcd.get(5, 0)
    
        2
  •  1
  •   Walter    14 年前

    item = len(abcd) > 5 and abcd[5] or 0 .

    非常重要 abcd[5] 在这种情况下)不得计算为布尔值 False 价值观。如果是,则上述语句将被计算为 0 而不是列表中的实际(假)值( None () {} 等)。