快速回答
这个问题在我刚开始学习 Python 的时候就出现了,我觉得值得在这里记录一下这个方法。只有一项检查用于模拟原始行为。
def list_range(start, stop=None, step=1):
if stop is None:
start, stop = 0, start
return list(range(start, stop, step))
我认为这个解决方案比使用所有关键字参数或*args
.
解释
使用哨兵
正确执行此操作的关键是使用哨兵对象来确定您是否获得第二个参数,如果没有,则在将第一个参数移动到第二个参数时为第一个参数提供默认值。
None
,作为 Python 的 null 值,是一个很好的最佳实践哨兵,检查它的惯用方法是使用关键字is
,因为它是一个单例。
带有正确文档字符串的示例,声明签名/API
def list_range(start, stop=None, step=1):
'''
list_range(stop)
list_range(start, stop, step)
return list of integers from start (default 0) to stop,
incrementing by step (default 1).
'''
if stop is None:
start, stop = 0, start
return list(range(start, stop, step))
示范
>>> list_range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list_range(5, 10)
[5, 6, 7, 8, 9]
>>> list_range(2, 10, 2)
[2, 4, 6, 8]
如果没有给出参数,它会引发错误,这与这里的全关键字解决方案不同。
警告
顺便说一句,我希望这只是读者从理论角度考虑的,我不认为这个功能值得维护,除非在中央规范位置使用以使 Python 2 和 3 之间的代码交叉兼容。 Python,使用内置函数将范围具体化为列表非常简单:
Python 3.3.1 (default, Sep 25 2013, 19:29:01)
[GCC 4.7.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]