尝试使用 _make 函数创建 namedtuple object 时出错

Getting error when trying to create namedtuple object using _make function

大家好我最近开始学习Pythoncollections模块。 当我尝试实现 namedtuple collections 进行练习时 我得到一个错误。我尝试在官方 Python 文档中搜索 但找不到。大家能帮帮我吗

我得到的错误是,即使我为 我正在获取 namedtuple 中的一些字段

#Importing namedtuple from collections module
from collections import namedtuple

#Creating a Student namespace
Students = namedtuple('Student','Roll_No Name Marks Percentage Grad', defaults= 
[0,''])
Students._field_defaults

#Creating students
ram = Students._make([101,'Ram Lodhe',[95,88,98]])
shaym = Students._make([101,'Shyam Verma',[65,88,85]])
geeta = Students._make([101,'Geeta Laxmi',[86,90,60]])
venkat = Students._make([101,'Venkat Iyer',[55,75,68]])
ankita = Students._make([101,'Anikta Gushe',[88,90,98]])
 TypeError  Traceback (most recent call last)  
 ram = Students._make([101,'Ram Lodhe',[95,88,98]])  
 TypeError: Expected 5 arguments, got 3

您的命名元组需要 5 个元组条目,但是,您提交了一个包含最后三个条目的列表(这是一个对象)。我修改了你的代码(命名很糟糕,如果你想保留,请更改)现在可以了。

Students = namedtuple('Student','Roll_No Name List_ofMarksPercentageGrad', defaults= 
[0,''])

到目前为止,我不知道有什么选项可以告诉 namedtuples 一个条目是一个包含命名条目的列表。

Per @jasonharper,_make() 似乎绕过了默认值。所以解决方法是直接构造命名元组:

ram = Students(101,'Ram Lodhe',[95,88,98])

或者,您可以手动将默认值传递给 _make():

ram = Students._make([101,'Ram Lodhe',[95,88,98], *Students._field_defaults.values()])