Python next() 函數(shù)

2019-03-16 11:27 更新

Python next() 函數(shù)

Python 內(nèi)置函數(shù) Python 內(nèi)置函數(shù)

描述

Python next() 返回迭代器的下一個項目。

語法

next 語法:

next(iterator[, default])

參數(shù)說明:

  • iterator:可迭代對象
  • default:可選,用于設(shè)置在沒有下一個元素時返回該默認(rèn)值,如果不設(shè)置,又沒有下一個元素則會觸發(fā) StopIteration 異常。

返回值

返回對象幫助信息。

實例

以下實例展示了 next 的使用方法:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 首先獲得Iterator對象:
it = iter([1, 2, 3, 4, 5])
# 循環(huán):
while True:
try:
# 獲得下一個值:
x = next(it)
print(x)
except StopIteration:
# 遇到StopIteration就退出循環(huán)
break

輸出結(jié)果為:

1
2
3
4
5

Python 內(nèi)置函數(shù) Python 內(nèi)置函數(shù)


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號