Python 3将范围转换为列表

问题:Python 3将范围转换为列表

我正在尝试列出其中的数字1-1000。显然,这会令人烦恼,因此我试图创建一个包含范围的列表。在Python 2中,似乎:

some_list = range(1,1000)

本来可以用,但是在Python 3中,范围类似于xrangePython 2?

谁能对此提供一些见识?

I’m trying to make a list with numbers 1-1000 in it. Obviously this would be annoying to write/read, so I’m attempting to make a list with a range in it. In Python 2 it seems that:

some_list = range(1,1000)

would have worked, but in Python 3 the range is similar to the xrange of Python 2?

Can anyone provide some insight into this?


回答 0

您可以从range对象构造一个列表:

my_list = list(range(1, 1001))

这也是您使用python2.x中的生成器进行操作的方式。通常来说,虽然您可能不需要列表,但因为可以得到my_list[i]更有效(i + 1)的值,如果只需要遍历该列表,则可以依靠range

另请注意,在python2.x上,xrange仍可索引1。这意味着range在python3.x上也具有相同的属性2

1print xrange(30)[12]适用于python2.x

2 python3.x中与1相似的语句是print(range(30)[12])并且也起作用。

You can just construct a list from the range object:

my_list = list(range(1, 1001))

This is how you do it with generators in python2.x as well. Typically speaking, you probably don’t need a list though since you can come by the value of my_list[i] more efficiently (i + 1), and if you just need to iterate over it, you can just fall back on range.

Also note that on python2.x, xrange is still indexable1. This means that range on python3.x also has the same property2

1print xrange(30)[12] works for python2.x

2The analogous statement to 1 in python3.x is print(range(30)[12]) and that works also.


回答 1

在Pythons <= 3.4中,您可以按照其他建议使用list(range(10)),以使列表超出范围(通常,任何可迭代的列表)。

在Python中3.5以解压缩概括引入的另一种替代方法是*在列表文字中使用[]

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

尽管这等效于list(r),但是它是字面语法,并且不涉及任何函数调用的事实确实使它执行得更快。如果您需要打高尔夫球,它的字符也更少:-)

In Pythons <= 3.4 you can, as others suggested, use list(range(10)) in order to make a list out of a range (In general, any iterable).

Another alternative, introduced in Python 3.5 with its unpacking generalizations, is by using * in a list literal []:

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

Though this is equivalent to list(r), it’s literal syntax and the fact that no function call is involved does let it execute faster. It’s also less characters, if you need to code golf :-)


回答 2

在Python 3.x中,该range()函数具有自己的类型。所以在这种情况下,您必须使用迭代器

list(range(1000))

in Python 3.x, the range() function got its own type. so in this case you must use iterator

list(range(1000))


回答 3

Python3缺少直接获取范围列表的功能的原因是因为最初的Python3设计器在Python2中是新手。他只考虑了range()在for循环中使用函数,因此,该列表永远不需要扩展。实际上,很多时候我们确实需要使用range()函数来生成列表并传递给函数。

因此,在这种情况下,与Python2相比,Python3不那么方便,因为:

  • 在Python2,我们xrange()range() ;
  • 在Python3,我们range()list(range())

尽管如此,您仍然可以通过以下方式使用列表扩展:

[*range(N)]

The reason why Python3 lacks a function for directly getting a ranged list is because the original Python3 designer was quite novice in Python2. He only considered the use of range() function in a for loop, thus, the list should never need to be expanded. In fact, very often we do need to use the range() function to produce a list and pass into a function.

Therefore, in this case, Python3 is less convenient as compared to Python2 because:

  • In Python2, we have xrange() and range();
  • In Python3, we have range() and list(range())

Nonetheless, you can still use list expansion in this way:

[*range(N)]

回答 4

您实际上不需要在列表中使用数字1-1000。但是,如果由于某些原因您确实需要这些数字,则可以这样做:

[i for i in range(1, 1001)]

清单理解概述:

上面的列表理解转换为:

nums = []
for i in range(1, 1001):
    nums.append(i)

尽管只是2.x版本,但这只是列表理解语法。我知道这可以在python 3中使用,但是不确定是否还有升级的语法

范围开始于第一个参数;但以不包括第二个参数为结束(当提供2个参数时;如果第一个参数保留,则其将从’0’开始)

range(start, end+1)
[start, start+1, .., end]

You really shouldn’t need to use the numbers 1-1000 in a list. But if for some reason you really do need these numbers, then you could do:

[i for i in range(1, 1001)]

List Comprehension in a nutshell:

The above list comprehension translates to:

nums = []
for i in range(1, 1001):
    nums.append(i)

This is just the list comprehension syntax, though from 2.x. I know that this will work in python 3, but am not sure if there is an upgraded syntax as well

Range starts inclusive of the first parameter; but ends Up To, Not Including the second Parameter (when supplied 2 parameters; if the first parameter is left off, it’ll start at ‘0’)

range(start, end+1)
[start, start+1, .., end]

回答 5

实际上,如果您想要1-1000(含),请使用range(...)带有参数1和1001:range(1, 1001)range(start, end)函数,因为该函数从开始到(结束-1)(含)。

Actually, if you want 1-1000 (inclusive), use the range(...) function with parameters 1 and 1001: range(1, 1001), because the range(start, end) function goes from start to (end-1), inclusive.


回答 6

在Python 3中使用范围

这是一个在两个数字之间返回的示例函数

def get_between_numbers(a, b):
    """
    This function will return in between numbers from two numbers.
    :param a:
    :param b:
    :return:
    """
    x = []
    if b < a:
        x.extend(range(b, a))
        x.append(a)
    else:
        x.extend(range(a, b))
        x.append(b)

    return x

结果

print(get_between_numbers(5, 9))
print(get_between_numbers(9, 5))

[5, 6, 7, 8, 9]  
[5, 6, 7, 8, 9]

Use Range in Python 3.

Here is a example function that return in between numbers from two numbers

def get_between_numbers(a, b):
    """
    This function will return in between numbers from two numbers.
    :param a:
    :param b:
    :return:
    """
    x = []
    if b < a:
        x.extend(range(b, a))
        x.append(a)
    else:
        x.extend(range(a, b))
        x.append(b)

    return x

Result

print(get_between_numbers(5, 9))
print(get_between_numbers(9, 5))

[5, 6, 7, 8, 9]  
[5, 6, 7, 8, 9]

回答 7

实际上,与Python2相比,这是对Python3的追溯。当然,使用range()和xrange()的Python2比分别使用list(range())和range()的Python3更方便。原因是因为Python3的原始设计人员经验不足,他们只考虑了许多初学者使用范围函数来遍历内存和CPU效率低下的大量元素。但是他们忽略了使用range函数生成数字列表。现在,对他们来说已经变回来为时已晚。

如果要成为Python3的设计师,我将:

  1. 使用irange返回序列迭代器
  2. 使用lrange返回序列表
  3. 使用range返回一个序列迭代器(如果元素数量很大,例如range(9999999))或一个序列列表(如果元素数量很小,例如range(10))

那应该是最佳的。

In fact, this is a retro-gradation of Python3 as compared to Python2. Certainly, Python2 which uses range() and xrange() is more convenient than Python3 which uses list(range()) and range() respectively. The reason is because the original designer of Python3 is not very experienced, they only considered the use of the range function by many beginners to iterate over a large number of elements where it is both memory and CPU inefficient; but they neglected the use of the range function to produce a number list. Now, it is too late for them to change back already.

If I was to be the designer of Python3, I will:

  1. use irange to return a sequence iterator
  2. use lrange to return a sequence list
  3. use range to return either a sequence iterator (if the number of elements is large, e.g., range(9999999) or a sequence list (if the number of elements is small, e.g., range(10))

That should be optimal.