range方法在Python2和Python3中的不同
2020-06-20 16:51
483 查看
range()方法是Python中常用的方法, 但是在Python2和Python3中使用方法不同,下面看下它们的不同使用方法。
range方法详解
range(start, stop[, step])
range是python中的其中一个内置函数
作用:可创建一个整数列表。一般用在 for 循环中。
参数说明:
start:起点,一般和stop搭配使用,既生成从start开始到stop结束(不包括stop)范围内的整数,例如:range(1,10),会生成[1,2,3,4,5,6,7,8,9]
stop:终点,可以和start搭配使用,也可以单独使用,既当start=0时,例如range(5) = range(0, 5)
step:步长,既下一次生成的数和这次生成的数的差,例如range(1, 10, 2) 生成[1,3,5,7,9],再如range(1,10,3) 生成[1, 4, 7]
代码示例:
Python 3.7.2 (default, Feb 12 2019, 08:15:36) [Clang 10.0.0 (clang-1000.11.45.5)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> for i in range(1,10, 1): ... print(i) ... >>>
使用区别
在python2中,range方法得到的结果就是一个确定的列表对象,列表对象所拥有的方法,range方法生成的结果对象都可以直接使用,而在python3中,range方法得到的对象是一个迭代器而不是一个确定的列表,如果想要转化为列表对象则需要再使用list方法进行转化。
for i in range(start, stop)在python2和python3中都可使用
代码实例:
Python3
Python 3.7.2 (default, Feb 12 2019, 08:15:36) [Clang 10.0.0 (clang-1000.11.45.5)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> for i in range(1,10, 1): ... print(i) ... >>>
Python2:
Python 2.7.10 (default, Aug 17 2018, 19:45:58) [GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> for i in range(1,10, 1): ... print(i) ... >>>
Python2直接生成列表,Python3需要配合list方法使用
Python3:
Python 3.7.2 (default, Feb 12 2019, 08:15:36) [Clang 10.0.0 (clang-1000.11.45.5)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> l = range(1, 10) >>> l range(1, 10) >>> type(l) <class 'range'> >>> l2 = list(l) >>> l2 [1, 2, 3, 4, 5, 6, 7, 8, 9] >>>
Python2:
Python 2.7.10 (default, Aug 17 2018, 19:45:58) [GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> l = range(1, 10) >>> l [1, 2, 3, 4, 5, 6, 7, 8, 9] >>>
Python3中range()方法生成的已经不是一个列表, 而是一个range的迭代器
相关文章推荐
- 用python实现5种不同回归方法
- windows和linux的转行符不同导致的Python无法执行的解决方法
- python 在不同层级目录import 模块的方法
- python 在不同层级目录import 模块的方法
- python中的一些遍历列表,元组,字符串等的方法,如:range,enumerate
- python 处理中文时出现的错误'ascii' codec can't decode byte 0xe9 in position 0: ordinal not in range(128)" 解决方法
- Python中不同进制的语法及转换方法分析
- windows下多版本python环境变量设置与pip不同版本方法(三步骤)
- Python不同目录间进行模块调用的实现方法
- Python2和Python3中除法操作/的不同
- python 在不同层级目录import 模块的方法-andersonyan-ChinaUnix博客
- 【python】numpy库ndarray多维数组的创建方法:np.array(list/tuple)、arange, ones, zeros等详解
- python多进程不同实现方法的异同点
- python在不同平台下的安装方法
- 在Python 不同级目录之间模块的调用方法
- Python不同方法实现手写数字识别结果和代码
- Python同个方法不同参数
- python分批定量读取文件内容,输出到不同文件中的方法
- python 在不同层级目录import 模块的方法
- python 在不同层级目录import 模块的方法