【问题标题】:Best way to make a function which can take a list or any number of arguments?制作一个可以接受列表或任意数量参数的函数的最佳方法是什么?
【发布时间】:2019-04-03 15:35:29
【问题描述】:

实现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

【问题讨论】:

  • 您是否尝试使用 map?,我不明白 args 是一个列表有什么问题,或者使用列表理解或映射,您可以执行 def for_each(func, args): return [ func(arg) 用于 args 中的 arg
  • @E.Serra 我只是希望我的函数的用户能够使用它来传递列表或单独传递参数。这只是一个非常简化的示例。
  • @ruohola 我的函数的第一个版本应该适合你,只需检查它是否是来自collections.abc.Iterable 的可迭代对象 :)

标签: python python-3.x function arguments


【解决方案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])

【讨论】:

  • 如果他们通过一个集合怎么办?和一个 int,你的所有将失败 is 实例,例如for_each(打印, [23, ['a', 'b']])
  • @E.Serra OP 没有要求他的 args 的 dfs 或 bfs,据我所知,他要求的深度为 1。他甚至没有要求第二种方法,这只是对 OP 的帮助。(我不知道您是否对这篇文章投了反对票,但请避免使用它以进行报复)
  • @E.Serra 这不需要处理嵌套列表
  • 仅供参考:如果参数是单个字符串,这将不起作用。但是话又说回来,OP没有提到这一点。
  • @quamrana 我希望它适用于任何类型的参数,因此它也适用于任意数量的字符串或字符串列表/元组。
【解决方案2】:

好的,现在我明白了你的问题:

不要这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多