1. 程式人生 > >Python 自定義iterator生成器

Python 自定義iterator生成器

#計數版
class countdown(object):
	def __init__(self,start):
		self.start = start
	def __iter__(self):
		return countdown_iter(self.start)

class countdown_iter(object):
	def __init__(self, count):
		self.count = count
	def __next__(self):
		if self.count <= 0:
			raise StopIteration
		r = self.count
		self.count -= 1
		return r

  

#pandas讀取多個檔案
import pandas as pd

class read_csv_paths(object):
	def __init__(self,paths):
		self.paths = paths
	def __iter__(self):
		return read_csv_iter(self.paths)

class read_csv_iter(object):
	def __init__(self, paths):
		self.paths = paths
	def __next__(self):
		if len(self.paths)<=0:
			raise StopIteration
		path=self.paths.pop()
		#print(path)
		df=pd.read_csv(path,low_memory=False,dtype='object')
		return df