我正在处理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")
这可能是一些新手问题,但这就是我的意思:)我将不胜感激!
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
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")