Namedtuple错误

ask*_*nce 2 python json arguments namedtuple

我正在尝试使用namedtuple将Python对象序列化为JSON.但是我得到了这个错误.谷歌没有帮助.

Traceback (most recent call last):
 File "cpu2.py", line 28, in <module>
 cpuInfo = collections.namedtuple('cpuStats',('cpu.usr', ('str(currentTime) + " " 
 +str(cpuStats[0]) + " host="+ thisClient')), ('cpu.nice', ('str(currentTime) + " " 
 +str(cpuStats[1]) + " host="+ thisClient')), ('cpu.sys',('str(currentTime) + " " 
 +str(cpuStats[2]) + " host="+ thisClient')), ('cpu.idle',('str(currentTime) + " " 
 +str(cpuStats[3]) + " host="+ thisClient')))
 TypeError: namedtuple() takes at most 4 arguments (5 given)
Run Code Online (Sandbox Code Playgroud)

mr2*_*ert 5

这是namedtuple文档的链接.您没有正确初始化它.

我猜你应该如何初始化它:

cpuInfo = collections.namedtuple('cpuStats', ['usr', 'nice', 'sys', 'idle'])

# In this case, usr=str(currentTime) + " " +str(cpuStats[0]) + " host=" + thisClient
# You can figure the rest out...
info = cpuInfo(usr='fill',
               nice='this',
               sys='your',
               idle='self')
Run Code Online (Sandbox Code Playgroud)

另外,您可能想要阅读这个讨论在json中序列化namedtuples的问题.