首页 > 解决方案 > 如何修复 Python 中的“__new__() 缺少 3 个必需的位置参数:..”错误

问题描述

我正在处理 python 代码,但出现此错误:“TypeError: new () missing 3 required positional arguments: 'name', 'freq', and 'gen'”

我正在导入一个 csv 文件来创建一个元组列表,使用命名元组。

import csv
from collections import namedtuple

Rec = namedtuple('Rec', 'year, name, freq, gen')

def read_file(file):  
    with open(file) as f:
        reader = csv.reader(f)
        next(reader)
        for line in reader:
            recs= Rec(line)
        return recs

read_file("./data/file.csv")

这可能是一些新手问题,但我就是这样:) 我会很感激任何帮助!

标签: pythonnamedtuple

解决方案


line是一个元组。当您调用Rec(line)时,整个元组将被解释为year参数(缺少其他三个参数,因此出现错误)。

要解决此问题,请更改

recs = Rec(line)

recs = Rec(*line)

或者

recs = Rec._make(line)

https://docs.python.org/2/library/collections.html#collections.somenamedtuple._make


推荐阅读