欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中迭代器的創(chuàng)建與使用詳解

 更新時間:2023年08月24日 09:38:48   作者:python收藏家  
Python中的迭代器是一個對象,用于迭代可迭代對象,如列表,元組,字典和集合,這篇文章主要為大家介紹了Python中迭代器的創(chuàng)建與使用,需要的可以參考下

Python中的迭代器是一個對象,用于迭代可迭代對象,如列表,元組,字典和集合。Python迭代器對象使用iter()方法初始化。它使用next()方法進行迭代。

  • iter():iter()方法用于迭代器的初始化。這將返回一個迭代器對象
  • next():next方法返回可迭代對象的下一個值。當我們使用for循環(huán)來遍歷任何可迭代對象時,它在內(nèi)部使用iter()方法來獲取迭代器對象,迭代器對象進一步使用next()方法進行迭代。此方法引發(fā)StopIteration以發(fā)出迭代結(jié)束的信號。

Python iter()示例

string = "GFG"
ch_iterator = iter(string)
print(next(ch_iterator))
print(next(ch_iterator))
print(next(ch_iterator))

輸出

G
F
G

使用iter()和next()創(chuàng)建迭代器

下面是一個簡單的Python迭代器,它創(chuàng)建了一個從10到給定限制的迭代器類型。例如,如果限制是15,則它會打印10 11 12 13 14 15。如果限制是5,則它不打印任何內(nèi)容。

# An iterable user defined type
class Test:
    # Constructor
    def __init__(self, limit):
        self.limit = limit
    # Creates iterator object
    # Called when iteration is initialized
    def __iter__(self):
        self.x = 10
        return self
    # To move to next element. In Python 3,
    # we should replace next with __next__
    def __next__(self):
        # Store current value ofx
        x = self.x
        # Stop iteration if limit is reached
        if x > self.limit:
            raise StopIteration
        # Else increment and return old value
        self.x = x + 1;
        return x
# Prints numbers from 10 to 15
for i in Test(15):
    print(i)
# Prints nothing
for i in Test(5):
    print(i)

輸出

10
11
12
13
14
15

使用iter方法迭代內(nèi)置迭代器

在下面的迭代中,迭代狀態(tài)和迭代器變量是內(nèi)部管理的(我們看不到它),使用迭代器對象遍歷內(nèi)置的可迭代對象,如列表,元組,字典等。

# Iterating over a list
print("List Iteration")
l = ["geeks", "for", "geeks"]
for i in l:
    print(i)
# Iterating over a tuple (immutable)
print("\nTuple Iteration")
t = ("geeks", "for", "geeks")
for i in t:
    print(i)
# Iterating over a String
print("\nString Iteration")   
s = "Geeks"
for i in s :
    print(i)
# Iterating over dictionary
print("\nDictionary Iteration")  
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
    print("%s  %d" %(i, d[i]))

輸出

List Iteration
geeks
for
geeks

Tuple Iteration
geeks
for
geeks

String Iteration
G
e
e
k
s

Dictionary Iteration
xyz  123
abc  345

可迭代 vs 迭代器(Iterable vs Iterator)

Python中可迭代對象和迭代器不同。它們之間的主要區(qū)別是,Python中的可迭代對象不能保存迭代的狀態(tài),而在迭代器中,當前迭代的狀態(tài)被保存。
注意:每個迭代器也是一個可迭代對象,但不是每個可迭代對象都是Python中的迭代器。

可迭代對象上迭代

tup = ('a', 'b', 'c', 'd', 'e')
for item in tup:
    print(item)

輸出

a
b
c
d
e

在迭代器上迭代

tup = ('a', 'b', 'c', 'd', 'e')
# creating an iterator from the tuple
tup_iter = iter(tup)
print("Inside loop:")
# iterating on each item of the iterator object
for index, item in enumerate(tup_iter):
    print(item)
    # break outside loop after iterating on 3 elements
    if index == 2:
        break
# we can print the remaining items to be iterated using next()
# thus, the state was saved
print("Outside loop:")
print(next(tup_iter))
print(next(tup_iter))

輸出

Inside loop:
a
b
c
Outside loop:
d
e

使用迭代器時出現(xiàn)StopIteration錯誤

Python中的Iterable可以迭代多次,但當所有項都已迭代時,迭代器會引發(fā)StopIteration Error。

在這里,我們試圖在for循環(huán)完成后從迭代器中獲取下一個元素。由于迭代器已經(jīng)耗盡,它會引發(fā)StopIteration Exception。然而,使用一個可迭代對象,我們可以使用for循環(huán)多次迭代,或者可以使用索引獲取項。

iterable = (1, 2, 3, 4)
iterator_obj = iter(iterable)
print("Iterable loop 1:")
# iterating on iterable
for item in iterable:
    print(item, end=",")
print("\nIterable Loop 2:")
for item in iterable:
    print(item, end=",")
print("\nIterating on an iterator:")
# iterating on an iterator object multiple times
for item in iterator_obj:
    print(item, end=",")
print("\nIterator: Outside loop")
# this line will raise StopIteration Exception
# since all items are iterated in the previous for-loop
print(next(iterator_obj))

輸出

Iterable loop 1:
1,2,3,4,
Iterable Loop 2:
1,2,3,4,
Iterating on an iterator:
1,2,3,4,
Iterator: Outside loop

Traceback (most recent call last):
  File "scratch_1.py", line 21, in <module>
    print(next(iterator_obj))
StopIteration

到此這篇關(guān)于Python中迭代器的創(chuàng)建與使用詳解的文章就介紹到這了,更多相關(guān)Python迭代器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 在jupyter notebook中調(diào)用.ipynb文件方式

    在jupyter notebook中調(diào)用.ipynb文件方式

    這篇文章主要介紹了在jupyter notebook中調(diào)用.ipynb文件方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-04-04
  • Python清空文件并替換內(nèi)容的實例

    Python清空文件并替換內(nèi)容的實例

    今天小編就為大家分享一篇Python清空文件并替換內(nèi)容的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-10-10
  • Django URL參數(shù)Template反向解析

    Django URL參數(shù)Template反向解析

    這篇文章主要介紹了Django URL參數(shù)Template反向解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-11-11
  • tensorflow查看ckpt各節(jié)點名稱實例

    tensorflow查看ckpt各節(jié)點名稱實例

    今天小編就為大家分享一篇tensorflow查看ckpt各節(jié)點名稱實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • 教你python制作自己的模塊的基本步驟

    教你python制作自己的模塊的基本步驟

    這篇文章主要介紹了python如何制作自己的模塊,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-08-08
  • python人工智能算法之線性回歸實例

    python人工智能算法之線性回歸實例

    這篇文章主要為大家介紹了python人工智能算法之線性回歸實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-03-03
  • 一份python入門應該看的學習資料

    一份python入門應該看的學習資料

    關(guān)于python入門你應該看這些資料,幫助你快速入門python,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-04-04
  • Python的Flask路由實現(xiàn)實例代碼

    Python的Flask路由實現(xiàn)實例代碼

    這篇文章主要介紹了Python的Flask路由實現(xiàn)實例代碼,在啟動程序時,python解釋器會從上到下對代碼進行解釋,當遇到裝飾器時,會執(zhí)行,并把函數(shù)對應的路由以字典的形式進行存儲,當請求到來時,即可根據(jù)路由查找對應要執(zhí)行的函數(shù)方法,需要的朋友可以參考下
    2023-08-08
  • python pygame實現(xiàn)五子棋小游戲

    python pygame實現(xiàn)五子棋小游戲

    這篇文章主要為大家詳細介紹了python pygame實現(xiàn)五子棋小游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-06-06
  • python的socket編程入門

    python的socket編程入門

    本篇文章是一篇關(guān)于python的socket編程入門教程,如果你也正好需要這方面的內(nèi)容,學習下吧。
    2018-01-01

最新評論