range() 不是每次都评估它的参数吗? [英] Does range() not evaluate its argument every time?

查看:20
本文介绍了range() 不是每次都评估它的参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

l 作为参数传递给 range 函数,该函数的值在 for 循环内被修改,但循环将用于 10 次而不是 5 次.

l is passed as an argument to range function whose value is modified inside for loop, but the loop is going for 10 times instead of 5.

i = 0
l = 10
for i in range(l):
    print i,l
    l = l-1

输出为

0 10
1 9
2 8
3 7
4 6
5 5
6 4
7 3
8 2
9 1

虽然我预料到了

0 10
1 9
2 8
3 7
4 6

range() 是第一次计算值还是其他原因?

Does range() evaluates value for the first time only or something else is the reason?

推荐答案

不,for 循环只对可迭代表达式求值一次.

No, the for loop evaluates the iterable expression just once.

range() 被调用一次,然后 for 循环遍历结果.

range() is called once, and the for loop then iterates over the result.

引用自 for 声明文档:

Quoting from the for statement documentation:

表达式列表求值一次;它应该产生一个可迭代的对象.

The expression list is evaluated once; it should yield an iterable object.

强调我的.

这篇关于range() 不是每次都评估它的参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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