简体   繁体   English

Python 的 range 函数是如何工作的?

[英]How does the Python's range function work?

If I write如果我写

for i in range(5):
      print i

Then it gives 0, 1, 2, 3, 4然后它给出 0, 1, 2, 3, 4
Does that mean Python assigned 0, 1, 2, 3, 4 to i at the same time?这是否意味着 Python 同时为 i 分配了 0、1、2、3、4?
However if I wrote:但是,如果我写道:

for i in range(5):
      a=i+1

Then I call a, it only gives 5然后我打电话给a,它只给5
But if I add ''print a'' it gives 1, 2, 3, 4, 5但是如果我添加 ''print a'' 它会给出 1, 2, 3, 4, 5
So my question is what is the difference here?所以我的问题是这里有什么区别?
Is ia string or a list or something else? ia 是字符串还是列表或其他什么?

Or maybe can anyone help me to sort out:或者也许有人可以帮我整理一下:

for l in range(5):
    #vs,fs,rs are all m*n matrixs,got initial values in,i.e vs[0],fs[0],rs[0] are known
    #want use this foor loop to update them
    vs[l+1]=vs[l]+fs[l]
    fs[l+1]=((rs[l]-re[l])
    rs[l+1]=rs[l]+vs[l]
#then this code gives vs,fs,rs

If I run this kind of code, then I will get the answer only when l=5如果我运行这种代码,那么只有当 l=5 时我才会得到答案
How can I make them start looping?我怎样才能让它们开始循环?

ie l=0 got values for vs[1],fs[1],rs[1],即 l=0 得到了 vs[1],fs[1],rs[1] 的值,
then l=1 got values for vs[2],rs[2],fs[2]......and so on.然后 l=1 得到了 vs[2],rs[2],fs[2]......等等的值。
But python gives different arrays of fs,vs,rs, correspond to different value of l但是python给出了不同的fs,vs,rs数组,对应不同的l值

How can I make them one piece?我怎样才能把它们做成一件?

A "for loop" in most, if not all, programming languages is a mechanism to run a piece of code more than once.在大多数(如果不是全部)编程语言中,“for 循环”是一种多次运行一段代码的机制。

This code:这段代码:

for i in range(5):
    print i

can be thought of working like this:可以认为是这样工作的:

i = 0
print i
i = 1
print i
i = 2
print i
i = 3
print i
i = 4
print i

So you see, what happens is not that i gets the value 0, 1, 2, 3, 4 at the same time , but rather sequentially.所以你看,什么情况是不是i得到值0,1,2,3,4与此同时,而是顺序。

I assume that when you say "call a, it gives only 5", you mean like this:我假设当你说“调用 a,它只给出 5”时,你的意思是这样的:

for i in range(5):
    a=i+1
print a

this will print the last value that a was given.这将打印给出的最后一个值。 Every time the loop iterates, the statement a=i+1 will overwrite the last value a had with the new value.每次循环迭代时,语句a=i+1将用新值覆盖 a 的最后a值。

Code basically runs sequentially, from top to bottom, and a for loop is a way to make the code go back and something again, with a different value for one of the variables.代码基本上按顺序从上到下运行,for 循环是一种使代码返回并再次执行某些操作的方法,其中一个变量具有不同的值。

I hope this answered your question.我希望这回答了你的问题。

When I'm teaching someone programming (just about any language) I introduce for loops with terminology similar to this code example:当我教某人编程(几乎任何语言)时,我都会使用类似于此代码示例的术语引入for循环:

for eachItem in someList:
    doSomething(eachItem)

... which, conveniently enough, is syntactically valid Python code. ...,这很方便,是语法上有效的 Python 代码。

The Python range() function simply returns or generates a list of integers from some lower bound (zero, by default) up to (but not including) some upper bound, possibly in increments (steps) of some other number (one, by default). Python range()函数简单地返回或生成一个整数列表,从某个下限(默认为零)到(但不包括)某个上限,可能以某个其他数字(默认为 1)的增量(步长) )。

So range(5) returns (or possibly generates ) a sequence: 0, 1, 2, 3, 4 (up to but not including the upper bound).因此range(5)返回(或可能生成)一个序列:0、1、2、3、4(直到但不包括上限)。

A call to range(2,10) would return: 2, 3, 4, 5, 6, 7, 8, 9range(2,10)调用将返回:2, 3, 4, 5, 6, 7, 8, 9

A call to range(2,12,3) would return: 2, 5, 8, 11range(2,12,3)调用将返回:2, 5, 8, 11

Notice that I said, a couple times, that Python's range() function returns or generates a sequence.请注意,我多次说过 Python 的range()函数返回或生成一个序列。 This is a relatively advanced distinction which usually won't be an issue for a novice.这是一个相对高级的区别,对于新手来说通常不会成为问题。 In older versions of Python range() built a list (allocated memory for it and populated with with values) and returned a reference to that list.在旧版本的 Python 中, range()构建了一个列表(为它分配了内存并填充了值)并返回了对该列表的引用。 This could be inefficient for large ranges which might consume quite a bit of memory and for some situations where you might want to iterate over some potentially large range of numbers but were likely to " break " out of the loop early (after finding some particular item in which you were interested, for example).这对于可能消耗相当多内存的大范围来说可能是低效的,并且在某些情况下,您可能想要迭代一些潜在的大范围数字,但可能会提前“ break ”循环(在找到某些特定项目之后)例如,您感兴趣的内容)。

Python supports more efficient ways of implementing the same semantics (of doing the same thing) through a programming construct called a generator . Python 支持通过称为generator的编程构造来实现相同语义(做相同的事情)的更有效方法。 Instead of allocating and populating the entire list and return it as a static data structure, Python can instantiate an object with the requisite information (upper and lower bounds and step/increment value) ... and return a reference to that. Python 无需分配和填充整个列表并将其作为静态数据结构返回,而是可以使用必要信息(上限和下限以及步长/增量值)实例化一个对象……并返回对该对象的引用。

The (code) object then keeps track of which number it returned most recently and computes the new values until it hits the upper bound (and which point it signals the end of the sequence to the caller using an exception called "StopIteration").然后(代码)对象跟踪它最近返回的数字并计算新值,直到它达到上限(并且它使用称为“StopIteration”的异常向调用者发出序列结束的信号)。 This technique (computing values dynamically rather than all at once, up-front) is referred to as "lazy evaluation."这种技术(预先动态计算而不是一次性计算所有值)被称为“惰性求值”。

Other constructs in the language (such as those underlying the for loop) can then work with that object (iterate through it) as though it were a list.语言中的其他结构(例如for循环的底层结构)可以与该对象一起工作(遍历它),就好像它是一个列表一样。

For most cases you don't have to know whether your version of Python is using the old implementation of range() or the newer one based on generators.在大多数情况下,您不必知道您的 Python 版本是使用range()的旧实现还是基于生成器的新实现。 You can just use it and be happy.您可以使用它并感到高兴。

If you're working with ranges of millions of items, or creating thousands of different ranges of thousands each, then you might notice a performance penalty for using range() on an old version of Python.如果您正在处理数百万个项目的范围,或者每个项目创建数千个不同的范围,那么您可能会注意到在旧版本的 Python 上使用range()导致性能下降。 In such cases you could re-think your design and use while loops, or create objects which implement the "lazy evaluation" semantics of a generator, or use the xrange() version of range() if your version of Python includes it, or the range() function from a version of Python that uses the generators implicitly.在这种情况下,您可以重新考虑您的设计并使用while循环,或者创建实现生成器“惰性求值”语义的对象,或者如果您的 Python 版本包含它,则使用range()xrange()版本,或者隐式使用生成器的 Python 版本中的range()函数。

Concepts such as generators, and more general forms of lazy evaluation, permeate Python programming as you go beyond the basics.当您超越基础知识时,诸如生成器之类的概念和更一般的惰性求值形式会渗透到 Python 编程中。 They are usually things you don't have to know for simple programming tasks but which become significant as you try to work with larger data sets or within tighter constraints (time/performance or memory bounds, for example).对于简单的编程任务,它们通常是您不必知道的事情,但是当您尝试使用更大的数据集或在更严格的限制(例如,时间/性能或内存限制)内时,它们变得很重要。

[Update: for Python3 (the currently maintained versions of Python) the range() function always returns the dynamic, "lazy evaluation" iterator; [更新:对于 Python3(当前维护的 Python 版本), range()函数总是返回动态的、“惰性求值”迭代器; the older versions of Python (2.x) which returned a statically allocated list of integers are now officially obsolete (after years of having been deprecated)].返回静态分配的整数列表的旧版本 Python (2.x) 现在正式过时(在多年被弃用之后)]。

for i in range(5):

是相同的

for i in [0,1,2,3,4]:

range(x) returns a list of numbers from 0 to x - 1. range(x)返回从 0 到x - 1 的数字列表。

>>> range(1)
[0]
>>> range(2)
[0, 1]
>>> range(3)
[0, 1, 2]
>>> range(4)
[0, 1, 2, 3]

for i in range(x): executes the body (which is print i in your first example) once for each element in the list returned by range() . for i in range(x):range()返回的列表中的每个元素执行一次主体(在您的第一个示例中为print i range() i is used inside the body to refer to the “current” item of the list. i在 body 内部用于引用列表的“当前”项目。 In that case, i refers to an integer, but it could be of any type, depending on the objet on which you loop.在这种情况下, i指的是一个整数,但它可以是任何类型,具体取决于您循环的对象。

The range function wil give you a list of numbers, while the for loop will iterate through the list and execute the given code for each of its items. range函数将为您提供一个数字列表,而for循环将遍历列表并为其每个项目执行给定的代码。

for i in range(5):
      print i

This simply executes print i five times, for i ranging from 0 to 4.这只是简单地执行print i五次,因为 i 的范围从 0 到 4。

for i in range(5):
      a=i+1

This will execute a=i+1 five times.这将执行a=i+1五次。 Since you are overwriting the value of a on each iteration, at the end you will only get the value for the last iteration, that is 4+1.由于要覆盖的价值a在每次迭代,最后你只会得到最后一次迭代,也就是4 + 1的值。

Useful links:有用的链接:
http://www.network-theory.co.uk/docs/pytut/rangeFunction.html http://www.network-theory.co.uk/docs/pytut/rangeFunction.html
http://www.ibiblio.org/swaroopch/byteofpython/read/for-loop.html http://www.ibiblio.org/swaroopch/byteofpython/read/for-loop.html

It is looping, probably the problem is in the part of the print...它正在循环,可能问题出在打印部分......

If you can't find the logic where the system prints, just add the folling where you want the content out:如果您找不到系统打印的逻辑,只需在您想要内容的位置添加以下内容:

for i in range(len(vs)):
    print vs[i]
    print fs[i]
    print rs[i]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM