我正试着列一个数字为1-1000的清单。显然,这将是令人讨厌的写/读,所以我试图使一个范围内的列表。在Python 2中,似乎:
some_list = range(1,1000)
会工作,但在Python 3中,范围类似于Python 2的xrange ?
有人能对此提供一些见解吗?
我正试着列一个数字为1-1000的清单。显然,这将是令人讨厌的写/读,所以我试图使一个范围内的列表。在Python 2中,似乎:
some_list = range(1,1000)
会工作,但在Python 3中,范围类似于Python 2的xrange ?
有人能对此提供一些见解吗?
当前回答
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.
如果我是Python3的设计者,我会:
使用irange返回一个序列迭代器 使用lrange返回一个序列列表 使用range返回序列迭代器(如果元素数量很大,例如range(9999999))或序列列表(如果元素数量很小,例如range(10))
这应该是最优的。
其他回答
Python 3:
my_list = [*range(1001)]
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.
如果我是Python3的设计者,我会:
使用irange返回一个序列迭代器 使用lrange返回一个序列列表 使用range返回序列迭代器(如果元素数量很大,例如range(9999999))或序列列表(如果元素数量很小,例如range(10))
这应该是最优的。
实际上,如果你想要1-1000(包括),使用带有参数1和1001的range(…)函数:range(1,1001),因为range(start, end)函数从start到(end-1),包括(end-1)。
你可以从range对象中构造一个列表:
my_list = list(range(1, 1001))
这是在python2中使用生成器的方法。X也是。通常来说,你可能不需要一个列表,因为你可以更有效地获得my_list[i]的值(i + 1),如果你只需要迭代它,你可以回到range。
还要注意在python2上。X, xrange仍然是可索引的。这意味着python3上的范围。X也有相同的性质2
1打印xrange(30)[12]适用于python2.x
在python3中类似于1的语句。X是print(range(30)[12]),同样有效。
在Python 3中使用Range。
下面是一个示例函数,返回两个数字之间的数字
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]