如何将功能应用于元组?
这应该很容易:如何将功能应用于Python的元组?
VIZ。:
Python 3.9.9 (main, Nov 16 2021, 09:34:38)
[Clang 13.0.0 (clang-1300.0.29.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def g(a,b):
... return a+b
...
>>> tup = (3,4)
>>>
>>> g(tup)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: g() missing 1 required positional argument: 'b'
>>> g.apply(tup)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'apply'
>>> apply(g,tup)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'apply' is not defined
我当然可以编写一个g
的版本,该版本期望元组,甚至是用于一般2 ARG函数的转换功能:
>>> def conv2(fun):
... def tuplefun(tup):
... (a,b) = tup
... return fun(a,b)
... return tuplefun
...
>>> tuple_g = conv2(g)
>>> tuple_g(tup)
7
...任意函数的一般情况。
(Obresearch:我在大约五分钟内搜索了这个问题的答案,发现了很多有关Pandas DataFrames的问题,但似乎没有一个可以回答这个问题的问题。我敢肯定,这很容易答案,我很抱歉没有发现它,但是如果我没有找到它,那么可能还有很多其他人……换句话说,“问题的重复#xxxxx”将在这里受到欢迎。
) ,我最喜欢的问题是完全相同的问题关于Scala语言,从2010年开始。我想我在生活中的角色是官能制作器划分的其他语言...?)
This should be an easy one: how do I apply a function to a tuple in Python?
Viz.:
Python 3.9.9 (main, Nov 16 2021, 09:34:38)
[Clang 13.0.0 (clang-1300.0.29.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def g(a,b):
... return a+b
...
>>> tup = (3,4)
>>>
>>> g(tup)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: g() missing 1 required positional argument: 'b'
>>> g.apply(tup)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'apply'
>>> apply(g,tup)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'apply' is not defined
I can certainly write a version of g
that expects a tuple, or even a conversion function that does it for a general 2-arg function:
>>> def conv2(fun):
... def tuplefun(tup):
... (a,b) = tup
... return fun(a,b)
... return tuplefun
...
>>> tuple_g = conv2(g)
>>> tuple_g(tup)
7
... but this doesn't work for the general case of an arbitrary-arity function.
(ObResearch: I searched for an answer to this question for about five minutes and found a whole bunch of questions about pandas dataframes but none that appeared to answer this question. I'm sure this has an easy answer, and I apologize for not finding it, but if I'm not finding it, then probably lots of others are too... in other words, a "duplicate of question #XXXXX" would be very welcome here.)
(As an ironic-to-me side note, my most-liked question is exactly this same question about the Scala language, from back in 2010. I guess my role in life is functional-programmer-raiding-other-languages...?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

您这样写:
You write it like this: