英文:
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')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论