简体   繁体   English

Python语言中的函数range()没有给出预期的结果

[英]Function range() in Python language does not give the expected result

As a beginner in python, I was trying to test the function range() in the IDLE terminal. 作为python的初学者,我试图在IDLE终端中测试函数range()。 I wrote in the terminal the below posted code and I expected to see result like this: 我在终端上写了下面发布的代码,我希望看到这样的结果:

range(10)==>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

But unfortunately, i do not get the expected result 但不幸的是,我没有得到预期的结果

Python Code I Tried: 我试过的Python代码:

range(10)
print(range(10))

The Result From The shell: 来自shell的结果:

>>>
print(range(10))

In python 3, range() returns a generator, that's why it shows you the object rather than the values: 在python 3中, range()返回一个生成器,这就是它向您显示对象而不是值的原因:

>>> print(range(10))
range(0, 10)

If you were expecting a list, you will need to convert it to one before printing it: 如果您期望列表,则需要在打印前将其转换为一个列表:

>>> print(list(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Generators only create one value at a time in order to save memory. 生成器一次只创建一个值以节省内存。 You can read up on them here , which includes an example suited to your test case. 您可以在这里阅读它们,其中包括适合您的测试用例的示例。


Cross version solution 跨版解决方案

C:\Documents and Settings\U009071\Desktop>python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> print(list(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>> for i in range(10):
...     print(i)
...
0
1
2
3
4
5
6
7
8
9
>>>

Python2: Python2:

>>> print(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a = range(10)
>>> print(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Don't know your Python version, but mine works fine. 不知道你的Python版本,但我的工作正常。 Try specifying range(0,10) to be sure. 请确保指定range(0,10)

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

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