具有负步幅的 Python range() [英] Python range() with negative strides

查看:44
本文介绍了具有负步幅的 Python range()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在步幅为 -1 的情况下使用 range() 函数?

Is there a way of using the range() function with stride -1?

例如使用 range(10, -10) 而不是下面的方括号值?

E.g. using range(10, -10) instead of the square-bracketed values below?

即以下行:

for y in range(10,-10)

代替

for y in [10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]:

显然,可以用另一种更优雅的循环来做到这一点,但 range() 示例对我想要的效果会更好.

Obviously one could do this with another kind of loop more elegantly but the range() example would work much better for what I want.

推荐答案

您可以指定步幅(包括负步幅)作为第三个参数,所以

You can specify the stride (including a negative stride) as the third argument, so

range(10,-11,-1)

给予

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10] 

一般来说,尝试不需要任何费用.您可以简单地将其输入到解释器中,然后查看它的作用.

In general, it doesn't cost anything to try. You can simply type this into the interpreter and see what it does.

这都是记录在这里:

range(start, stop[, step])

但主要是我想鼓励你玩玩,看看会发生什么.如您所见,您的直觉很准.

but mostly I'd like to encourage you to play around and see what happens. As you can see, your intuition was spot on.

这篇关于具有负步幅的 Python range()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆