【问题标题】:Is there a "get or default" way to access lists? [duplicate]是否有访问列表的“获取或默认”方式? [复制]
【发布时间】:2015-05-23 03:03:00
【问题描述】:

我喜欢 get 函数,它可以提供默认值,但这只适用于字典。

s=dict{}
s.get("Ann", 0)

我为列表写了类似的东西。 Python3.4中是否已经存在这个函数?

def get(s, ind):
    return len(s)>ind and s[ind] or 0

【问题讨论】:

  • 明确地说,您的意思是按价值获取,对吗?您提出的实施令人困惑。
  • 你为什么使用and s[ind]

标签: python list python-3.x


【解决方案1】:

不,lists 不存在这样的内置方法。找出列表索引是否有效是微不足道的,因此不需要函数。你可以直接把你的函数中的代码(或者更易读的s[ind] if ind < len(s) else 0)直接放到需要的两三个地方,这样就完全可以理解了。

(当然,您的代码假定ind 始终为正数...)

如果您确实想编写一个函数,请将其设为 list 子类的方法。

【讨论】:

    【解决方案2】:

    没有像 get 这样的方法来获取列表,但您可以使用 itertools.islicenext,默认值为 0:

    from itertools import islice
    def get(s, ind):
        return next(islice(s, ind, ind + 1), 0)
    

    如果ind 的值是0NoneFalse 等任何虚假值,则在您的代码中使用and s[ind] 将返回默认的0。这可能不是您想要的.

    如果您想为错误值返回默认值并处理负索引,您可以使用abs

    def get(s, ind):
        return s[ind] or 0 if len(s) > abs(ind) else 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-20
      • 2011-11-16
      • 2016-04-27
      • 2017-03-26
      • 1970-01-01
      • 2017-04-15
      相关资源
      最近更新 更多