Pythonic获取数组元素或默认值如果不存在

问题描述

| 我们有
matches = re.findall(r\'somewhat\',\'somewhere\')
我们可以简化一下吗
if len(matches) > index:
    return matches[index]
else:
    return \'default\'
要么
return matches[index] if len(mathes) > index else \'default\'
类似于JS \
return matches[index] || \'default\'
我们可以简单地使用
return \'somewhere\'.match(/somewhat/)[index] || \'default\'
    

解决方法

        这样的事情可能会有所帮助:
>>> reg = re.compile(\'-\\d+-\')
>>> reg.findall(\'a-23-b-12-c\') or [\'default\']
[\'-23-\',\'-12-\']
>>> reg.findall(\'a-b-c\') or [\'default\']
[\'default\']
编辑 丑陋的单线
(reg.findall(\'a-b-c\')[index:] or [\'default\'])[0]
    ,        我很想尝试使用try除块。不过,您需要考虑何时索引为负。这是错误还是可接受的输入? 但是以下方法会起作用:
try:
    return re.findall(r\'somewhat\',\'somewhere\')[index]
except IndexError:
    return \'default\'
如果您担心效率,则这是首选方法,因为它避免了两次检查数组的边界(一次手动检查一次,而python进行内部检查则第二次)。 编辑:我从未特别喜欢这种方式,因为它隐藏了子调用引发的任何IndexErrors并会返回默认值(我怀疑这是否是所需的行为以及可能的错误源)。     ,        并非如此,因为以无效索引运行
mathes[x]
会抛出
IndexError
,而不会返回
False
。     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...