如何将一个函数映射到命名元组的所有元素?

huangapple go评论54阅读模式
英文:

How to map a function to all elements of a namedtuple?

问题

以下是您要的翻译部分:

我有一些 `namedtuple`,我想对其成员应用一个函数然后使用相同名称的处理后元素创建一个新的 `namedtuple`。

from collections import namedtuple

def fun(val):
    if val is None:
        return "Unknown"
    return f"'{val}'"

我尝试过基本的映射到构造函数但我不知道 `namedtuple` 的元素或类型是什么

processed_tuple = namedtuple(map(fun, some_tuple))


processed_tuple = namedtuple(*map(fun, some_tuple))

不起作用

`some_tuple` 在运行时构造可以具有不同的字段名称例如一个人但我在此之前不知道

Person = namedtuple("Person", ["Firstname", "Lastname"])
some_tuple = Person("Foo", None)

然后处理后的 `namedtuple` 应该如下所示 `(Firstname='Foo', Lastname='Unknown')`

是否有一种通用方法还是我必须事先知道成员
英文:

I have some namedtuple which I want to apply a function on its members and then create a new namedtuple with the processed elements of the same name.

from collections import namedtuple

def fun(val):
    if val is None:
        return "Unknown"
    return f"'{val}'"

I tried a basic map to the constructor but I don't know the elements or type of the namedtuple

processed_tuple = namedtuple(map(fun, some_tuple))

or

processed_tuple = namedtuple(*map(fun, some_tuple))

do not work.

some_tuple is constructed at runtime and can have different fieldnames. For example a person but I don't know that before:

Person = namedtuple("Person", ["Firstname", "Lastname"])
some_tuple = Person("Foo", None)

The processed namedtuple should then look like (Firstname="'Foo'", Lastname="Unknown")

Is there a generic approach or do I have to know the members before hand?

答案1

得分: 1

不确定这是否是您想要的

```python
from inspect import signature
from collections import namedtuple

Person = namedtuple("Person", ["Firstname", "Lastname"])
some_tuple = Person("Foo", None)

def fun(val):
    if val is None:
        return "Unknown"
    return f"'{val}'"

processed_tuple = namedtuple('X', signature(type(some_tuple)).parameters
                             )._make(map(fun, some_tuple))

或者:

processed_tuple = namedtuple('X', some_tuple._fields
                             )._make(map(fun, some_tuple))

输出:

X(Firstname="'Foo'", Lastname='Unknown')
英文:

Not fully sure if this is what you want:

from inspect import signature
from collections import namedtuple

Person = namedtuple("Person", ["Firstname", "Lastname"])
some_tuple = Person("Foo", None)

def fun(val):
    if val is None:
        return "Unknown"
    return f"'{val}'"

processed_tuple = namedtuple('X', signature(type(some_tuple)).parameters
                             )._make(map(fun, some_tuple))

Or:

processed_tuple = namedtuple('X', some_tuple._fields
                             )._make(map(fun, some_tuple))

Output:

X(Firstname="'Foo'", Lastname='Unknown')

huangapple
  • 本文由 发表于 2023年6月15日 16:26:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480544.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定