如何修复“ __new __()缺少3个必需的位置参数:..”的Python错误

问题描述 投票:0回答:2

我正在处理python代码,但出现此错误:“ TypeError:new()缺少3个必需的位置参数:'name','freq'和'gen'”]

我正在导入一个csv文件以使用namedtuple创建元组列表。

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")

这可能是一些新手问题,但这就是我的意思:)我将不胜感激!

python namedtuple
2个回答
1
投票

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


-1
投票

namedtuple需要三个参数,但您只给出了一个。使用加星标的方法

recs = Rec(*line)

或完整代码->

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")
© www.soinside.com 2019 - 2024. All rights reserved.