要列出的 Python 范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33699896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:48:19  来源:igfitidea点击:

Python range to list

python

提问by Chucks

I am trying to convert a range to list.

我正在尝试将范围转换为列表。

nums = []
for x in range (9000, 9004):
    nums.append(x)
    print nums

output

输出

[9000]
[9000, 9001]
[9000, 9001, 9002]
[9000, 9001, 9002, 9003]

I just need something like

我只需要像

 [9000, 9001, 9002, 9003]

How do I get just the requred list ?

我如何获得所需的列表?

采纳答案by shubham

Since you are taking the print statement under the for loop, so just placed the print statement out of the loop.

由于您在 for 循环下使用 print 语句,因此只需将 print 语句放在循环之外。

nums = []
for x in range (9000, 9004):
    nums.append(x)
print (nums)

回答by ergonaut

You can just assign the range to a variable:

您可以将范围分配给变量:

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

In your case:

在你的情况下:

>>> nums = range(9000,9004)
>>> nums
[9000, 9001, 9002, 9003]
>>> 

However, in python3you need to qualify it with a list()

但是,python3您需要使用 list() 对其进行限定

>>> nums = list(range(9000,9004))
>>> nums
[9000, 9001, 9002, 9003]
>>> 

回答by Alastair McCormack

The output of range is a list:

range 的输出是一个列表:

>>> print range(9000, 9004)
[9000, 9001, 9002, 9003]

回答by Neil

Python 3

蟒蛇 3

For efficiency reasons, Python no longer creates a list when you use range. The new range is like xrangefrom Python 2.7. It creates an iterable range object that you can loop over or access using [index].

出于效率原因,当您使用range. 新范围类似于xrangePython 2.7。它创建了一个可迭代的范围对象,您可以使用[index].

If we combine this with the positional-expansion operator *, we can easily generate lists despite the new implementation.

如果我们将它与位置扩展运算符结合起来*,尽管有新的实现,我们仍然可以轻松生成列表。

[*range(9000,9004)]

Python 2

蟒蛇 2

In Python 2, rangedoes create a list... so:

在 Python 2 中,range确实创建了一个列表......所以:

range(9000,9004)