实现for_each
函数的正确方法是什么,以便它可以使用任意数量的参数,列表或元组作为参数?
def do_something(arg):
print("done", arg)
def for_each(func, *args):
if len(args) == 1: # How to do this, since this gives an
args = args[0] # error if there's only one parameter besides func?
for arg in args:
func(arg)
for_each(do_something, 1, 2)
for_each(do_something, ['foo', 'bar'])
for_each(do_something, (3, 4, 5))
输出:
done 1 done 2 done foo done bar done 3 done 4 done 5
实现此目标的正确方法是什么?因为这样调用会破裂:
for_each(do_something, 1)
Traceback (most recent call last): File "main.py", line 12, in <module> for_each(do_something, 1) File "main.py", line 8, in for_each for arg in args: TypeError: 'int' object is not iterable
答案 0 :(得分:1)
您要检查您的第一个元素是列表还是元组,如下所示:
(您需要检查实例,以防用户仅使用一个int实例,否则代码将失败)
def for_each(func, *args):
if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)): # You can even check on Iterable by importing collections.abc.Iterable
args = args[0]
for arg in args:
func(arg)
但是,您可以走得更远,让用户输入多个Iterable
,而不仅仅是元组或列表,例如:
from collections.abc import Iterable
from itertools import chain
def do_something(arg):
print("done", arg)
def for_each(func, *args):
if all(map(lambda x: isinstance(x, Iterable), args)) and not any(map(lambda x: isinstance(x, str), args)):
args = chain(*args)
for arg in args:
func(arg)
for_each(do_something, [0, 1], [0, 2])
答案 1 :(得分:0)
好,现在我明白了您的问题:
不要这样做:
if len(args) == 1: # is there really no cleaner
args = args[0] # way to do this part?
只要您不需要返回,只想调用一个函数,这看起来就更漂亮了。
def for_each(func, *args):
for arg in args:
if any([isinstance(args, myiter) for myiter in [tuple, list, set]]):
[for_each(func, arg) for arg in args]
else:
func(args)
for_each(do_something, 1, 2)
for_each(do_something, ['foo', 'bar'])
for_each(do_something, (3, 4, 5))
done 1
done 2
done foo
done bar
done 3
done 4
done 5
for_each(do_something, 1)
done 1