当前第2页 返回上一页
1 2 3 4 5 6 | def createList(r1, r2):
return [item for item in range(r1, r2+1)]
r1, r2 = -2, 4
print (createList(r1, r2))
r1, r2 = -4,6
print (createList(r1, r2))
|
输出:
1 2 | [-2, -1, 0, 1, 2, 3, 4]
[-4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6]
|
方法三:使用Pythonrange()
python中有一个range()函数,它从开始到结束创建一个数字序列,并在序列中输出每个项目。我们将range()与r1和r2一起使用,然后将序列转换为list。
示例:
1 2 3 4 5 6 | def createList(r1, r2):
return list(range(r1, r2+1))
r1, r2 = -2, 4
print (createList(r1, r2))
r1, r2 = -4,6
print (createList(r1, r2))
|
输出:
1 2 | [-2, -1, 0, 1, 2, 3, 4]
[-4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6]
|
方法四:使用numpy.arange()
python numpy.arange()会根据间隔返回元素间距均匀的列表。在这里,我们根据需要将间隔设置为1,以获得所需的输出。
示例:
1 2 3 4 5 | import numpy as np
def createList(r1, r2):
return np.arange(r1, r2+1, 1)
r1, r2 = -2, 3
print (createList(r1, r2))
|
输出:
相关视频教程推荐:《Python教程》
以上就是本篇文章的全部内容,希望能对大家的学习有所帮助。更多精彩内容大家可以关注php中文网相关教程栏目!!!
以上就是Python如何创建指定范围的数字列表?(代码示例)的详细内容,更多文章请关注木庄网络博客!!
返回前面的内容
相关阅读 >>
Python中正则表达式的简单介绍(附代码)
Python针对excel表格的操作
Python可以引用另一个文件的函数吗
Python作业:直方图、均衡化、高斯滤波
Python中(urlparse)模板的使用详解
Python file seek() 方法是什么?怎么理解并使用它?
Python如何遍历列表所有元素?
Python是一种什么样的语言?为什么要学习Python
如何用Python整理附件
什么是爬虫?Python网络爬虫中概念的介绍
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python如何创建指定范围的数字列表?(代码示例)