Skip to main content
 首页 » 编程设计

python之namedtuple 字段名称 : single string or sequence

2024年10月17日8jackei

Python 允许在命名元组的声明中提供 field_names 作为字符串序列或作为单个字符串,每个名称由空格和/或逗号分隔。

根据官方文档,首选方式似乎是Python 2是按顺序提供名称:

field_names are a sequence of strings such as ['x', 'y']. Alternatively, field_names can be a single string with each fieldname separated by whitespace and/or commas, for example 'x y' or 'x, y'.

在 Python 3 中首选项更改为单字符串版本:

field_names are a single string with each fieldname separated by whitespace and/or commas, for example 'x y' or 'x, y'. Alternatively, field_names can be a sequence of strings such as ['x', 'y'].

这背后有什么原因吗?

乍一看,我会说单字符串版本效率较低,因为它需要拆分输入。该序列对我来说似乎也更具可读性。哪个效率更高?

请您参考如下方法:

是的,在将其内容映射到 str 之前,提供 str 涉及 .replace 和 .split , see source :

if isinstance(field_names, str): 
    field_names = field_names.replace(',', ' ').split() 
field_names = list(map(str, field_names)) 

这显然比您提供列表要花费更多的时间。虽然,这应该永远不会成为性能瓶颈,它只会在对生成类的 namedtuple 的初始调用期间执行;随后的调用不必对它做任何事情。简而言之,不要担心这里的性能。