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

Python iterator

編輯:Python
# Get all the methods of an object :dir()
s = 'hello world'
l = [1, 2, 3]
print(dir(s))
print(dir(l))
# Iteratable object : The interior contains __iter__ Object of method 
# Iteratible objects cannot pass directly through for The loop takes values directly 
# Now we can directly do... On the iteratable object for Value cycle , because for Internal transformation has been made , First convert the iteratable object into an iterator , Reuse next Take the value 
print('__iter__' in dir(s))
# iterator : The interior contains __iter__ Method and contains __next__ Object of method ( File handle )
# advantage : Save memory 、next once , Take only one value .
with open('test', encoding='utf-8', mode='w') as f:
pass
print('__iter__' in dir(f) and '__next__' in dir(f)) # True
# Iteratable objects can be converted to iterators 
strs = 'hello world'
ret1 = iter(strs)
ret2 = strs.__iter__()
print(ret1, ret2)
# Value iterator : next() Methods or .__next__() Method , once next() Take a value 
res = iter(strs)
print(next(res)) # h
print(res.__next__()) # e
l1 = [11, 33, 44, 55, 66, 77]
# List to iterator 
ret = iter(l1)
print(ret)
for i in range(len(l1)):
print(next(ret))
# utilize while Loop simulation for The mechanism of loop fetching iteratable objects .( interview )
ss = 'asdfghjkl'
obj = iter(ss) # Convert an iteratable object to an iterator 
while True:
try:
print(next(obj))
except StopIteration:
break

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