问题描述
设 x 和 y 是两个整数:
Let x and y be two integers :
如何在 Python 中考虑 range(x,y)
这样的 x>y
?
我在 python 2.7 和 python 3.3 中都尝试了以下代码:
How range(x,y)
such x>y
would be considered in Python ?
I tried following code in both python 2.7 and python 3.3:
for i in range(10,3):
print i
我认为 range(10,3) 应该被视为列表 [0,3,6,9],但这部分代码没有渲染任何东西.
I thought range(10,3) should be considered as the list [0,3,6,9], but this portion of code isn't rendering anything.
推荐答案
您有两个选择:
重新排列输入值,
rearrange the input values,
range(0, 10, 3) # => (0, 3, 6, 9)
编写一个包装函数,为您重新排列它们:
write a wrapper function which rearranges them for you:
def safe_range(a, b):
return range(0, max(a,b), min(a,b))
safe_range(3, 10) # => (0, 3, 6, 9)
再想一想,我明白了;你试图做类似的事情
after thinking about it a bit more, I see; you were trying to do something like
range({start=0,} stop, step)
但是如果你只给出两个值,就无法区分它和
but if you only give two values there is no way to tell the difference between that and
range(start, stop, {step=1})
为了解决这个歧义,Python 语法要求默认值参数只能出现在所有位置参数之后——也就是说,第二个例子是有效的 Python,第一个不是.
To resolve this ambiguity, Python syntax demands that default-value parameters can only appear after all positional parameters - that is, the second example is valid Python, the first isn't.
这篇关于Python:如果 x>y,range(x,y) 的输出是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!