Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pythonic get数组元素,如果它不';不存在_Python_List_Element_Default - Fatal编程技术网

Pythonic get数组元素,如果它不';不存在

Pythonic get数组元素,如果它不';不存在,python,list,element,default,Python,List,Element,Default,我们有 我们能简化这个吗 matches = re.findall(r'somewhat', 'somewhere') 或 类似于JS的东西 return matches[index] if len(mathes) > index else 'default' 我们可以简单地使用 return matches[index] || 'default' 不完全是这样,因为使用无效索引运行mathes[x]将抛出索引器,该索引器不会返回False类似的内容可能会有所帮助: return '

我们有

我们能简化这个吗

matches = re.findall(r'somewhat', 'somewhere')

类似于JS的东西

return matches[index] if len(mathes) > index else 'default'
我们可以简单地使用

return matches[index] || 'default'

不完全是这样,因为使用无效索引运行
mathes[x]
将抛出
索引器,该索引器不会返回
False

类似的内容可能会有所帮助:

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']

我很想使用try-except块。但是,当索引为负值时,您需要考虑。这是错误还是可接受的输入

但以下方法可行:

(reg.findall('a-b-c')[index:] or ['default'])[0]
如果您关心效率,这是首选方法,因为它避免了两次检查数组的边界(一次是手动检查,另一次是python进行内部检查)


编辑:我从来没有特别喜欢这种方式,因为它隐藏了子调用抛出的任何索引器,并将返回默认值(我怀疑这是期望的行为,也是可能的错误源)。

JavaScript解决方案并非在所有情况下都能工作(例如,当
mathes[index]==0
)。同意。不是全部,但在大多数实际情况下。哦,我不知道空数组被认为是错误的。Thanks我相信使用
try except
s比检查数组长度(甚至两次)效率低。嗯,你可能是对的。我想我从dicts中得出了一个错误的类比,在dicts中try/except比d.has_key(k)/d[k要好。我做了一些测试。答案取决于你认为最有可能的结果。当索引存在时,try/except块的速度是检查列表边界速度的两倍。当它不存在时,try/except块将慢5倍。
(reg.findall('a-b-c')[index:] or ['default'])[0]
try:
    return re.findall(r'somewhat', 'somewhere')[index]
except IndexError:
    return 'default'