Python 3.2 空闲:范围函数 - 打印还是列表?
我知道这是错误的做法,但我正在使用 python 3,但使用 python 2 书来学习它。
它说,
>>>range(2,7)
将显示
[2,3,4,5,6]
,但我知道它不会显示上面的输出,这是我想的。所以我尝试了:
>>>>print(range(2,7))
和 ta-da- 它显示如下:
range(2,7)
看起来这是从 P2 到 P3 的更改之一,所以我尝试了:
list(range(2,7))
这个在 IDLE 上可以正常工作,但在记事本上不能用于长编码。所以最后我尝试了:
print(list(range(2,7)))
它显示了与我想要的类似的东西......我做得对吗?这是唯一的写法吗?
I know this is wrong thing to do, but I am using python 3 but studying it with python 2 book.
it says,
>>>range(2,7)
will show
[2,3,4,5,6]
but I know it won't show the output above, THAT I figured. so I tried:
>>>>print(range(2,7))
and ta-da- it shows follow:
range(2,7)
looks like this is the one of changes from P2 to P3 so I tried:
list(range(2,7))
this one works ok on IDLE but not ok on notepad for long coding. so finally I tried:
print(list(range(2,7)))
and it showed something similar to what I intended... Am I doing right? Is this the only way to write it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的唯一目标是取回列表表示,那么您所做的就是正确的。 Python 3.0 现在将
range
视为返回迭代器(xrange
过去是这样做的)If your only goal is to get back the list representation, what you're doing is correct. Python 3.0 now treats
range
as returning an iterator (whatxrange
used to do)在 IDLE 情况下,您正在 IDLE 的 PyShell 窗口中运行代码。这正在运行交互式解释器。在交互模式下,Python 会立即解释您输入的每一行,并显示通过评估您输入的语句以及写入标准输出或标准错误的任何内容而返回的值。对于 Python 2,
range()
返回一个列表,正如您所发现的,在 Python 3 中,它返回一个可迭代的range()
对象,您可以使用该对象创建列表对象或在迭代上下文中的其他地方使用。 Python 3 range() 类似于 Python 2 的 xrange()。当您在记事本等编辑器中编辑文件时,您正在编写一个脚本文件,当您在 Python 解释器中运行该文件时,整个脚本将被解释并作为一个单元运行,即使它只有一行长。在屏幕上,您只能看到写入标准输出(即“
print()
”)或标准错误(即错误回溯)的内容;您不会像在交互模式下那样看到每个语句的评估结果。因此,在您的示例中,当从脚本文件运行时,如果您不打印评估某些内容的结果,您将看不到它。Python 教程在此处对此进行了一些讨论。
In your IDLE case, you are running the code in IDLE's PyShell window. This is running the interactive interpreter. In interactive mode, Python interprets immediately each line you type in and it displays the value returned by evaluating the statement you typed plus anything written to standard output or standard error. For Python 2,
range()
returns a list and, as you discovered, in Python 3, it returns an iterablerange()
object which you can use to create a list object or use elsewhere in iteration contexts. The Python 3 range() is similar to Python 2's xrange().When you edit a file in an editor like Notepad, you are writing a script file and when you run the file in the Python interpreter, the whole script is interpreted and run as a unit, even if it is only one line long. On the screen, you only see what is written to standard output (i.e. "
print()
") or standard error (i.e. error tracebacks); you don't see the results of the evaluation of each statement as you do in interactive mode. So, in your example, when running from a script file, if you don't print the results of evaluating something you won't see it.The Python tutorial talks a bit about this here.