Assign a range to a variable (Python)

后端 未结 3 986
醉酒成梦
醉酒成梦 2021-01-12 16:00

Whenever I try to assign a range to a variable like so:

Var1 = range(10, 50)

Then try to print the variable:

Var1 = range(1         


        
3条回答
  •  再見小時候
    2021-01-12 16:36

    This is something that was changed in Python 3.0. You could recreate a similar function in Python 2.7 like so,

    def range(low, high=None):
      if high == None:
        low, high = 0, low
      i = low
      while i < high:
        yield i
        i += 1
    

    The benefit of this, is that the list doesn't have to be created before its used.

    for i in range(1,999999):
      text = raw_input("{}: ".format(i))
      print "You said {}".format(text)
    

    Which works like this:

    1: something
    You said something
    2: something else
    You said something else
    3: another thing
    You said another thing
    

    In Python 3.X, if we never get to the end of our loop (999997 iterations), it will never calculate all of the items. In Python 2.7 it has to build the entire range initially. In some older Python implementations, this was very slow.

提交回复
热议问题