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

标签 python list element default

我们有

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]

关于Pythonic 获取数组元素,如果不存在则获取默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6258081/

相关文章:

python - 使用 Django Admin 上传文件

python - 确定两个列表/数组的混洗索引

c# - xmldoc.Childnodes.item() 问题

python - Pandas DataFrame 到包含标题的列表列表

Python 3 基类类型注解只允许当前子类

python - Pip 列表因 AssertionError 崩溃

c# - 将 Javascript 数组转换为 C# 列表

c++ - 在 C++ 中使用邻接表的图形

list - 在 Flutter/Dart 中映射多个列表?

C++ - 推回队列列表