2

为方便起见,我想将单个值、列表或多个值的迭代器传递给函数。理想情况下,有一种方法可以从单个项目生成迭代器,以便一个循环可以容纳所有三种变体。

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):
4

3 回答 3

3
def flexible_func(param):
    try:
        # If it's any kind of iterable, you can iterate over it
        for x in mystery_wrapper(param):
            do_something(x)
    except TypeError:
        # Not iterable, so it's a single item
        do_something(param)

如果你担心do_something抛出 TypeError,你可以iter(param)单独测试

def flexible_func(param):
    try:
        iterable = iter(param)
    except TypeError:
        iterable = [param]
    for x in iterable:
        do_something(x)

装饰器版本

def mystery(func):
    def inner(arg):
        try:
            return func(iter(arg))
        except TypeError:
            return func([arg])
    return inner

@mystery
def flexible_func(param):
    for x in param:
        do_something(x)
于 2013-07-09T05:25:21.907 回答
2

你在寻找这样的东西吗?

def wrapper(arg):
        try:
            for ar in arg:
                yield ar
        except:
            yield arg

然后将其用作

for x in wrapper(range(1,5)):
    print x

或者

for x in wrapper(1):
    print x
于 2013-07-09T05:33:24.960 回答
1

这是另一种方式:

import collections

def flexible_func(*param):
    li=[]
    for x in param:
        if isinstance(x,collections.Iterable):
            for y in x:
                li.append(y)
        else:
            li.append(x)
    do_something(li)

def do_something(li):
    for x in li:
        print x

if __name__ == '__main__':
    flexible_func('single')
    flexible_func(['one', 'two'])
    flexible_func(range(6))
于 2013-07-09T05:39:14.370 回答