如何修复 Python 中的“__new__() 缺少 3 个必需的位置参数:..”错误
How to fix "__new__() missing 3 required positional arguments:.." error in Python
我正在编写 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")
这可能是一些新手问题,但我就是这样:)
如果有任何帮助,我将不胜感激!
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
我正在编写 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")
这可能是一些新手问题,但我就是这样:) 如果有任何帮助,我将不胜感激!
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