程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Usage of Python enumerate, ITER

編輯:Python

1、enumerate

 Add a subscript to a traversable object , Combine into a new sequence
enumerate(sequence , [start = 0])
for example :
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
for i,j in enumerate(seasons,start = 1):
print(i,j)
Output :
1 Spring
2 Summer
3 Fall
4 Winter
Is to add a subscript to each item of a traversable sequence , Then form a tuple , And form a new sequence .

2、 iterator iter()
Iteration is a way to access collection elements , Can remember the traversal location of the object , Access... From the first element of the collection , Until all elements are accessed . Iterators can only move forward and not backward .
There are two basic ways to iterator :iter() and next().
character string , List or tuple objects can be used to create iterators .

iter(object[, sentinel])
Parameter Introduction :
object: A collection of objects that support iteration .
sentinel -- If the second argument is passed , The parameter object Must be a callable object ( Such as , function ).
here ,iter An iterator object is created , Each time this iterator object is called __next__() When the method is used , Will be called object.
for example :
lst = [1,2,3,4]
for i in iter(lst):
print(i)
Output :
1
2
3
4
Use next Method
x = iter(lst)
print(next(x))# Output 1
print(next(x))# Output 2
print(next(x))# Output 3
# In fact, the execution process of the iterator can be regarded as the traversal of a single linked list .

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved