我使用namedtuple来保存字符串集及其相应的值。 我不使用字典,因为我希望字符串可以作为属性访问。在
我的代码是:
from collections import namedtuple
# Shortened for readability :-)
strings = namedtuple("strings", ['a0', 'a1', 'a2', ..., 'a400'])
my_strings = strings(value0, value1, value2, ..., value400)
理想情况下,一旦my_strings
被初始化,我应该能够执行以下操作:
并将value1
打印回来。在
但是我得到了以下错误:
strings(value0, value1, value2, ...value400)
^SyntaxError: more than 255 arguments
似乎python函数(包括namedtuple的init())在调用时不接受超过255个参数。 有没有办法绕过这个问题,让命名元组包含超过255个项目?为什么有255个参数的限制?在
namedtuple
开箱即用不支持您正在尝试的操作。在因此,下面的方法可能会达到目标,这可能会从}参数,或者更小更理智。在
400
变为{For more light on the subject.
这是对CPython函数定义的限制;在python3.7之前的版本中,不能为可调用函数指定超过255个显式参数。这适用于任何函数定义,而不仅仅是命名元组。在
请注意,在python3.7及更新版本中,这个限制已经被取消,新的限制是
sys.maxint
。见What is a maximum number of arguments in a Python function?它是为这个类生成的极限。定义的函数参数不能超过255个;因此,在CPython实现中无法实现结果类的
__new__
类方法。在不过,你得问问自己,你是否真的应该使用不同的结构。在我看来,你有一个类似于列表的数据;400个编号的名字是你的data bleeding into your names的标志。在
您可以通过手动创建自己的子类来解决此问题:
这个版本的命名元组完全避免了长参数列表,但在其他方面的行为与原始元组完全相同。有些冗长的^{。注意
_fields
属性的构造;将其替换为您自己的tuple字段。在传入生成器表达式以设置参数:
^{pr2}$或者如果您有一个值列表:
这两种技术都绕过了函数签名和函数调用参数计数的限制。在
演示:
这是我的版本
namedtuple
的替代版本,它支持255个以上的参数。这个想法不是为了功能上的对等,而是为了在某些方面有所改进(在我看来)。这仅适用于Python 3.4+:这可能不是最有效的方法,如果您正在进行大量的单独查找,将其内部转换为
dict
可能更好。一旦我有更多的时间或者至少看看性能有什么不同,我就开始优化版本。在相关问题 更多 >
编程相关推荐