为方便起见,我想将单个值、列表或多个值的迭代器传递给函数。理想情况下,有一种方法可以从单个项目生成迭代器,以便一个循环可以容纳所有三种变体。
def flexible_func(param):
for x in mystery_wrapper(param):
do_something(x)
flexible_func('single')
flexible_func(['one', 'two'])
flexible_func(generator)
这是我最终选择的:
from collections import Iterable
def iterate(seq_or_single):
if isinstance(seq_or_single, Iterable) and not isinstance(seq_or_single, basestring):
return seq_or_single
return [seq_or_single]
# for x in iterate(param):