generator

How to wrap or embed generators?

狂风中的少年 提交于 2020-12-26 07:42:08
问题 I'm trying to provide a unified interface for retrieving all files from a single directory or a list of directories. def get_files(dir_or_dirs): def helper(indir): file_list = glob.glob("*.txt") for file in file_list: yield file if type(dir_or_dirs) is list: # a list of source dirs for dir in dir_or_dirs: yield helper(dir) else: # a single source dir yield helper(dir_or_dirs) def print_all_files(file_iter): for file in file_iter: print(file) # error here! Questions: The error says 'file' is

Why can a python generator only be used once? [duplicate]

喜欢而已 提交于 2020-11-25 04:40:16
问题 This question already has answers here : Understanding generators in Python (12 answers) Closed 2 years ago . Once I use a generator once, it can't be used again. Why is this? Consider the following code: def generator(n): a = 1 for _ in range(n): yield a a += 1 def run_generator(generator): for a in generator: print(a, end = " ") If I were to execute this: count_generator = generator(10) run_generator(count_generator) run_generator(count_generator) It would only print: 1 2 3 4 5 6 7 8 9 10

Why can a python generator only be used once? [duplicate]

旧巷老猫 提交于 2020-11-25 04:38:53
问题 This question already has answers here : Understanding generators in Python (12 answers) Closed 2 years ago . Once I use a generator once, it can't be used again. Why is this? Consider the following code: def generator(n): a = 1 for _ in range(n): yield a a += 1 def run_generator(generator): for a in generator: print(a, end = " ") If I were to execute this: count_generator = generator(10) run_generator(count_generator) run_generator(count_generator) It would only print: 1 2 3 4 5 6 7 8 9 10