目錄python
def forl(iterable): iterator = iterable.__iter__() while True: try: print(iterator.__next__()) except Exception as e: print(e) break forl([1,2,3,4,5,6,7,8,9])
__iter__
方法的對象__iter__
方法的對象__iter__
方法獲得的返回值,而且可迭代對象會有一個__next___
方法__next__
方法,執行該方法會拿到迭代器對象中一個值__iter__
方法,執行該方法會拿到迭代器自己len()
方法獲取長度__iter__
後仍是迭代器自己,所以for循環不用考慮in後面的對象是可迭代對象仍是迭代器對象__iter__
方法後變成一個可迭代器對象,這個迭代器對象只是佔用了一小塊內存空間,只有使用__next__
後纔會取出一個值。x = 20 y = 10 print(f"x if x > y else y: {x if x >y else: y}")
it = [i for i in range(10)] it = [i**2 for i in range(10)] # i**2 -->改變 ,range(n) --可迭代對象 print(it)
dic = {} dic = {i:i*2 for i in range(10)} print(dic)
it1 = ['a','b','c'] it2 = ['1','2','3'] dic = {k: v for k,v in zip(it1,it2)} print(dic) for -- 循環內有常處理
t = (i for i in range(10)) print(t) print(f"next(t): {next(t)}」)
import sys sys.setrecursionlimit(10000) def foo(n): print('from foo',n) foo(n+1) foo(0)
nums = [1,3,7,11,22,34,55,78,111,115] for item in nums: if item == 10: print('find it') break else: print('not exists') 列表元素多:--二分查找 def search(search_num, nums): mid_index = len(nums)//2 print(nums) if not nums: print('not exists') return if search_num > nums[mid_index]: # in the right nums = nums[mid_index+1:] #切片 search(search_num, nums) elif search_num < nums[mid_index]: # in the left nums = nums[:mid_index] search(search_num, nums) else: print('find it') search(7, nums)