Python 的 next(~)
方法返回迭代器中的下一項。
參數
1. iterator
| iterator
我們應該返回下一個項目的迭代器。
2. default
| any
| optional
當我們到達迭代器末尾時要返回的值。
返回值
返回值取決於以下情況:
案子 |
返回值 |
---|---|
尚未耗盡迭代器中的所有項目 |
迭代器中的下一項 |
已用盡迭代器和提供的 |
|
已用盡迭代器中的所有項目,並且未提供 |
錯誤 |
例子
基本用法
要獲取迭代器中的下一項test
:
a = ['hi', 'bye', 'see you']
# converting the list to an iterator called test
test = iter(a)
print(next(test))
print(next(test))
print(next(test))
hi
bye
see you
請注意,每次調用 next(~)
方法時,我們都會返回迭代器 test
中的下一項。
默認參數
指定 'This is the default value'
的默認值:
b = ['hi', 'bye', 'see you']
# converting the list to an iterator called test
test = iter(b)
print(next(test, 'This is the default value'))
print(next(test, 'This is the default value'))
print(next(test, 'This is the default value'))
print(next(test, 'This is the default value'))
hi
bye
see you
This is the default value
在第四次調用 next(~)
方法時,我們返回 'This is the default value'
,因為我們已經耗盡了迭代器 test
中的所有項目。
StopIteration錯誤
如果我們不提供 default
值並且到達迭代器的末尾:
c = ['hi', 'bye', 'see you']
# converting the list to an iterator called test
test = iter(c)
print(next(test))
print(next(test))
print(next(test))
print(next(test))
hi
bye
see you
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-11-74eba8c03080> in <module>
7 print(next(test))
8 print(next(test))
----> 9 print(next(test))
StopIteration:
我們看到,由於迭代器 test
中沒有更多項,因此引發了 StopIteration
異常。
相關用法
- Python BeautifulSoup next_sibling屬性用法及代碼示例
- Python BeautifulSoup next_element屬性用法及代碼示例
- Python next()用法及代碼示例
- Python BeautifulSoup next_siblings屬性用法及代碼示例
- Python BeautifulSoup next_elements屬性用法及代碼示例
- Python networkx.algorithms.shortest_paths.weighted.all_pairs_dijkstra_path用法及代碼示例
- Python networkx.classes.function.edge_subgraph用法及代碼示例
- Python networkx.algorithms.tree.mst.maximum_spanning_edges用法及代碼示例
- Python networkx.algorithms.bipartite.basic.color用法及代碼示例
- Python networkx.algorithms.bipartite.cluster.latapy_clustering用法及代碼示例
- Python networkx.readwrite.json_graph.adjacency_data用法及代碼示例
- Python networkx.algorithms.bipartite.edgelist.generate_edgelist用法及代碼示例
- Python networkx.Graph.neighbors用法及代碼示例
- Python networkx.DiGraph.__contains__用法及代碼示例
- Python networkx.drawing.nx_pylab.draw_random用法及代碼示例
- Python networkx.convert_matrix.to_pandas_edgelist用法及代碼示例
- Python networkx.DiGraph.__init__用法及代碼示例
- Python networkx.algorithms.cycles.recursive_simple_cycles用法及代碼示例
- Python networkx.drawing.layout.random_layout用法及代碼示例
- Python networkx.algorithms.link_prediction.within_inter_cluster用法及代碼示例
- Python networkx.algorithms.non_randomness.non_randomness用法及代碼示例
- Python networkx.algorithms.traversal.depth_first_search.dfs_tree用法及代碼示例
- Python networkx.MultiGraph.clear用法及代碼示例
- Python networkx.algorithms.operators.product.cartesian_product用法及代碼示例
- Python networkx.algorithms.traversal.depth_first_search.dfs_labeled_edges用法及代碼示例
注:本文由純淨天空篩選整理自Arthur Yanagisawa大神的英文原創作品 Python | next method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。