range方法在Python2和Python3中的不同



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的迭代器

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM