制作可以带有列表或任意数量参数的函数的最佳方法? [英] Best way to make a function which can take a list or any number of arguments?
问题描述
实现for_each
函数的正确方法是什么,以便它可以采用任意数量的参数,列表或元组作为参数?
What's the correct way of implementing the for_each
function so that it can take any number of argument or a list or a tuple as parameter?
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
实现此目标的正确方法是什么?因为这样调用会破裂:
What's the correct way to achieve this? Since this will break if called like this:
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
推荐答案
您要检查您的第一个元素是列表还是元组,如下所示:
You want to check if your first element is a list or a tuple like this:
(您需要检查实例,以防用户仅使用一个int实例,否则您的代码将失败)
(You need to check the instance, in case user just use a single int for instance, your code would fail)
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
,而不仅仅是元组或列表,例如:
However, you can go further and let the user input several Iterable
and not only tuples or lists, such as follow :
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])
这篇关于制作可以带有列表或任意数量参数的函数的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!