顺序未知时在范围上进行迭代的Pythonic方法

Dut*_*taA 4 python loops python-3.x

说我有2个变量xy,我想遍历其间的所有值,而不知道是否xy更大:

if(x>y):
  for i in range(y,x):
    #Code

elif(x<y):
  for i in range(x,y):
    #Code
Run Code Online (Sandbox Code Playgroud)

没有所有if-else条件的Pythonic方法是什么?顺序无关紧要,降序或升序都可以,但是一般的答案会很好!

Flo*_*n H 8

怎么样:

for i in range(min(x,y), max(x,y)):
    ...
Run Code Online (Sandbox Code Playgroud)


Chr*_*ris 5

另一种方法是sorted拆包一起使用:

x, y = 10, 1
for i in range(*sorted([x,y])):
    print(i)
Run Code Online (Sandbox Code Playgroud)

输出:

1
2
3
...
Run Code Online (Sandbox Code Playgroud)