如何实现一个函数来覆盖单个值和多个值
假设您有一个像这样的值:
n = 5
和一个返回它的阶乘的函数,如下所示:
factorial(5)
如何处理多个值:
nums = [1,2,3,4,5]
factorial (nums)
因此它以列表形式返回所有这些值的阶乘?
在不编写 2 个方法的情况下,处理这个问题最干净的方法是什么? Python 有没有好的方法来处理这种情况?
Say you have a value like this:
n = 5
and a function that returns the factorial of it, like so:
factorial(5)
How do you handle multiple values:
nums = [1,2,3,4,5]
factorial (nums)
so it returns the factorials of all these values as a list?
What's the cleanest way to handle this, without writing 2 methods? Does Python have a good way to handle these kinds of situations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果它是可迭代的,则递归应用。 否则,正常进行。
或者,您可以将最后一个
return
移至except
块中。如果您确定 Factorial 的主体永远不会引发 TypeError ,则可以将其简化为:
If it's iterable, apply recursivly. Otherwise, proceed normally.
Alternatively, you could move the last
return
into theexcept
block.If you are sure the body of
Factorial
will never raiseTypeError
, it could be simplified to:列表理解:
编辑:
抱歉,我误解了,你想要一个处理序列和单个值的方法吗? 我无法想象为什么你不使用两种方法来做到这一点。
另一种选择是进行某种类型检查,最好避免这种情况,除非您有一些非常令人信服的理由这样做。
编辑2:
MizardX的答案更好,投票给那个答案。 干杯。
List comprehension:
EDIT:
Sorry, I misunderstood, you want a method that handles both sequences and single values? I can't imagine why you wouldn't do this with two methods.
The alternative would be to do some sort of type-checking, which is better avoided unless you have some terribly compelling reason to do so.
EDIT 2:
MizardX's answer is better, vote for that one. Cheers.
有时会这样做。
它提供了一个几乎神奇的函数,可以处理简单的值和序列。
This is done sometimes.
It gives an almost magical function that works with simple values as well as sequences.
如果你问 Python 是否可以进行方法重载:不能。 因此,像这样执行多方法是一种相当不符合 Python 风格的定义方法的方式。 此外,命名约定通常是大写的类名和小写的函数/方法。
如果你想继续,最简单的方法就是创建一个分支:
或者,如果你感觉很奇特,你可以创建一个对任何函数执行此操作的装饰器:
尽管更Pythonic的方法是使用可变参数长度:
将两者放在一起成为一个深度映射装饰器:
If you're asking if Python can do method overloading: no. Hence, doing multi-methods like that is a rather un-Pythonic way of defining a method. Also, naming convention usually upper-cases class names, and lower-cases functions/methods.
If you want to go ahead anyway, simplest way would be to just make a branch:
Or, if you're feeling fancy, you could make a decorator that does this to any function:
Although a more Pythonic way is to use variable argument lengths:
Putting the two together into a deep mapping decorator:
您可能想看看 NumPy/SciPy 的 向量化。
在 numpy 世界中,给定您的 single-int-arg Factorial 函数,
你会做类似的事情
,但请注意,最后一种情况返回单元素 numpy 数组而不是原始 int。
You might want to take a look at NumPy/SciPy's vectorize.
In the numpy world, given your single-int-arg Factorial function,
you'd do things like
although note that the last case returns a single-element numpy array rather than a raw int.
或者,如果您不喜欢列表理解语法,并且希望跳过新方法:
Or if you don't like the list comprehension syntax, and wish to skip having a new method: