目錄
基礎 Python 學習路線推薦 : Python 學習目錄 >> Python 基礎入門
Python 3.x 內置函數 next 可以從迭代器中檢索下一個元素或者數據,可以用於迭代器遍歷,使用的時候注意會觸發 StopIteration 異常!
一.Python next 函數簡介
'''
參數描述:
iterator – 迭代器;
default – 可選參數;如果不設置的話,當迭代器沒有下一個元素時,會拋StopIteration 異常;如果設置了該參數,沒有下一個元素時,默認返回該參數;
返回值:返回迭代器中當前元素的下一個元素;
'''
next(iterator[,default])
二.Python next 函數使用
1.沒有設置 default 參數,使用 next 函數時,如果沒有下一個元素或者數據,會拋 StopIteration 異常,注意異常處理;
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:猿說編程
@Blog(個人博客地址): www.codersrc.com
@File:Python next 函數.py
@Time:2021/05/10 07:37
@Motto:不積跬步無以至千里,不積小流無以成江海,程序人生的精彩需要堅持不懈地積累!
"""
>>> a = iter('1234')
>>> next(a)
'1'
>>> next(a)
'2'
>>> next(a)
'3'
>>> next(a)
'4'
>>> next(a) # 沒有下一個元素的時候使用next,直接拋異常 StopIteration
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
next(a)
StopIteration
2.使用 default 參數,使用 next 函數,如果沒有下一個元素或者數據,返回 default 值;
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:猿說編程
@Blog(個人博客地址): www.codersrc.com
@File:Python next 函數.py
@Time:2021/05/10 07:37
@Motto:不積跬步無以至千里,不積小流無以成江海,程序人生的精彩需要堅持不懈地積累!
"""
>>> a = iter('1234')
>>> next(a,'e')
'1'
>>> next(a,'e')
'2'
>>> next(a,'e')
'3'
>>> next(a,'e')
'4'
>>> next(a,'e') # 沒有下一個元素的時候使用next,直接返回default參數
'e'
>>> next(a,'e')
'e'
三.猜你喜歡
- Python 條件推導式
- Python 列表推導式
- Python 字典推導式
- Python 不定長參數 *argc/**kargcs
- Python 匿名函數 lambda
- Python return 邏輯判斷表達式
- Python is 和 == 區別
- Python 可變數據類型和不可變數據類型
- Python 淺拷貝和深拷貝
- Python 異常處理
- Python 線程創建和傳參
- Python 線程互斥鎖 Lock
- Python 線程時間 Event
- Python 線程條件變量 Condition
- Python 線程定時器 Timer
- Python 線程信號量 Semaphore
- Python 線程障礙對象 Barrier
- Python 線程隊列 Queue – FIFO
- Python 線程隊列 LifoQueue – LIFO
- Python 線程優先隊列 PriorityQueue
- Python 線程池 ThreadPoolExecutor(一)
- Python 線程池 ThreadPoolExecutor(二)
- Python 進程 Process 模塊
- Python 進程 Process 與線程 threading 區別
- Python 進程間通信 Queue / Pipe
- Python 進程池 multiprocessing.Pool
- Python GIL 鎖
未經允許不得轉載:猿說編程 » Python next 函數
本文由博客 - 猿說編程 猿說編程 發布!