如何迭代单个或多个项目?

时间:2013-07-09 05:20:06

标签: python iterator

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

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

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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

答案 2 :(得分: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))