我如何生成连续数字列表?[重复]
- 2025-04-17 09:02:00
- admin 原创
- 15
问题描述:
假设你8
在 Python 中输入了一个数字,并且想要生成一个连续数字列表,最多可以8
包含
[0, 1, 2, 3, 4, 5, 6, 7, 8]
你怎么能这样做?
解决方案 1:
range
在 Python 3 中,你可以像这样使用内置函数
>>> list(range(9))
[0, 1, 2, 3, 4, 5, 6, 7, 8]
注1: Python 3.x 的range
函数返回一个对象。如果您想要一个列表,则需要使用我在答案中展示的函数range
将其显式转换为列表。list
注2:我们将数字9传递给range
函数,因为range
函数会生成直到给定数字的数字,但不包括该数字。因此,我们给出实际数字+1。
注 3:range
Python 2 和 3 的功能略有不同。您可以在此答案中阅读更多相关信息。
解决方案 2:
使用 Python 的内置范围函数:
Python 2
input = 8
output = range(input + 1)
print output
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Python 3
input = 8
output = list(range(input + 1))
print(output)
[0, 1, 2, 3, 4, 5, 6, 7, 8]
解决方案 3:
以下是使用 numpy 生成从 0 到 100 的 n 个连续且间隔相等的数字的方法:
import numpy as np
myList = np.linspace(0, 100, n)
解决方案 4:
再举一个例子,尽管 range(value) 是迄今为止最好的方法,但这可能会在以后的其他方面对您有所帮助。
list = []
calc = 0
while int(calc) < 9:
list.append(calc)
calc = int(calc) + 1
print list
[0, 1, 2, 3, 4, 5, 6, 7, 8]
解决方案 5:
注意:-在 python-3x 中,你需要使用Range 函数,它可以按需生成数字,使用Range 函数创建连续数字列表的标准方法是
x=list(range(10))
#"list"_will_make_all_numbers_generated_by_range_in_a_list
#number_in_range_(10)_is_an_option_you_can_change_as_you_want
print (x)
#Output_is_ [0,1,2,3,4,5,6,7,8,9]
此外,如果您想使用Range 函数来生成连续数字列表,请观看此代码!
def consecutive_numbers(n) :
list=[i for i in range(n)]
return (list)
print(consecutive_numbers(10))
祝你好运!
解决方案 6:
你可以用它itertools.count()
来生成无界序列。(itertools 位于 Python 标准库中)。文档链接:
https://docs.python.org/3/library/itertools.html#itertools.count
解决方案 7:
根据您想要的结果,您还可以在 for 循环中打印每个数字:
def numbers():
for i in range(int(input('How far do you wanna go? '))+1):
print(i)
例如,如果用户输入的是 7:
How far do you wanna go? 7
0
1
2
3
4
5
6
7
您还可以删除 for 循环中的“+1”并将其放在打印语句上,这会将其更改为从 1 开始而不是从 0 开始。
解决方案 8:
您可以使用列表推导来解决这个问题,因为它只需两行就可以解决它。
n = int(input("Enter the range of the list:
"))
l1 = [i for i in range(n)] #Creates list of numbers in the range 0 to n
print(l1)
扫码咨询,免费领取项目管理大礼包!