开发者

For-loops in Python

开发者 https://www.devze.com 2022-12-26 19:43 出处:网络
What is the best way of doing this in Python? for (v = n / 2 - 1; v >= 0; v--) I 开发者_StackOverflow中文版actually tried Google first, but as far as I can see the only solution would be to use

What is the best way of doing this in Python?

for (v = n / 2 - 1; v >= 0; v--)

I 开发者_StackOverflow中文版actually tried Google first, but as far as I can see the only solution would be to use while.


I would do this:

for i in reversed(range(n // 2)):
    # Your code
    pass

It's a bit clearer that this is a reverse sequence, what the lower limit is, and what the upper limit is.


The way to do it is with xrange():

for v in xrange(n // 2 - 1, -1, -1):

(Or, in Python 3.x, with range() instead of xrange().) // is flooring division, which makes sure the result is a whole number.


for v in range(n//2, -1, -1)

However, in 90% of the cases when you would have used a for loop in C/Java/C#/VB, what you really want is list comprehension:

listOfStuff = [doSomethingWith(v) for v in range(n//2, -1, -1)]


for v in xrange(n/2 - 1, 0, -1):
   #your code here

Where v and n are ints or treated as ints. This means that the division will be an integer division, i.e., 1/2 == 0 is True.

Note: This is for Python 2.x .

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号