如何创建一个 slice() 对象,以便它包含列表/字符串的最后一个元素
s = 'abcdef'
s[slice(2,4)]
Run Code Online (Sandbox Code Playgroud)
工作正常。
假设我想获取从第二个到最后的元素,相当于s[2:]
s[slice(2)] # only gives first two elements, argument is interpreted as the end of the range
s[slice(2,)] # same as above
s[slice(2, -1)] # gives a range from second to the end excluding the last element
s[slice(2, 0)] # gives empty as expected, since end of range before the start
Run Code Online (Sandbox Code Playgroud)
我可以使用 专门获取最后一个元素slice(-1, -2, -1),这对于多个元素将无法正常工作。
假设我有这样的声明
logging.debug('%r', do_really_expensive_computation())
or
logging.debug('%r', find_my_object().do_really_expensive_computation())
Run Code Online (Sandbox Code Playgroud)
当日志记录级别设置为以上时,DEBUG它不会记录日志,但它仍然会在调用之前评估参数logging.debug(),并且执行do_really_expensive_computation()也find_my_object()可能相当繁重。
当低于当前级别时,是否有任何好的模式可以跳过日志记录中涉及的所有计算?