每当我尝试像这样给变量分配一个范围时:
Var1 = range(10, 50)然后尝试打印变量:
Var1 = range(10, 50)
print(Var1)它只是打印“range(10,50)”,而不是列表中的所有数字。为什么会这样呢?
发布于 2013-08-12 08:16:52
这一点在Python3.0中有所改变。您可以在Python2.7中重新创建类似的函数,如下所示:
def range(low, high=None):
if high == None:
low, high = 0, low
i = low
while i < high:
yield i
i += 1这样做的好处是,在使用列表之前不必创建列表。
for i in range(1,999999):
text = raw_input("{}: ".format(i))
print "You said {}".format(text)它是这样工作的:
1: something
You said something
2: something else
You said something else
3: another thing
You said another thing在Python3.x中,如果我们永远不会到达循环的末尾(999997次迭代),它将永远不会计算所有的项。在Python2.7中,它必须首先构建整个范围。在一些旧的Python实现中,这是非常慢的。
https://stackoverflow.com/questions/18177919
复制相似问题