问题描述
实现 for_each
函数的正确方法是什么,以便它可以接受任意数量的参数或列表或元组作为参数?
def do_something(arg):打印(完成",arg)def for_each(func, *args):if len(args) == 1: # 如何做到这一点,因为这给出了args = args[0] # 如果除了 func 只有一个参数会出错?对于 args 中的 arg:功能(参数)for_each(do_something, 1, 2)for_each(do_something, ['foo', 'bar'])for_each(do_something, (3, 4, 5))
输出:
done 1完成 2完成 foo完成吧完成 3完成 4完成 5
实现这一目标的正确方法是什么?因为如果这样调用它会中断:
for_each(do_something, 1)
回溯(最近一次调用最后一次):文件main.py",第 12 行,在 <module> 中for_each(do_something, 1)文件main.py",第 8 行,在 for_each 中对于 args 中的 arg:类型错误:int"对象不可迭代
您想检查您的第一个元素是列表还是元组,如下所示:
(您需要检查实例,例如,如果用户只使用单个 int,您的代码将失败)
def for_each(func, *args):if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)): # 你甚至可以通过导入 collections.abc.Iterable 来检查 Iterableargs = args[0]对于 args 中的 arg:功能(参数)
但是,您可以更进一步,让用户输入多个 Iterable
而不仅仅是元组或列表,例如:
from collections.abc import Iterable从 itertools 导入链def do_something(arg):打印(完成",arg)def for_each(func, *args):如果所有(map(lambda x: isinstance(x, Iterable), args)) 而不是任何(map(lambda x: isinstance(x, str), args)):args = 链(* args)对于 args 中的 arg:功能(参数)for_each(do_something, [0, 1], [0, 2])
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))
What's the correct way to achieve this? Since this will break if called like this:
for_each(do_something, 1)
You want to check if your first element is a list or a tuple like this:
(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)
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])
这篇关于制作可以接受列表或任意数量参数的函数的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!