我正在處理 python 代碼,但出現此錯誤:“TypeError: new () missing 3 required positional arguments: 'name', 'freq', and 'gen'”我正在導入一個 csv 文件來創建一個元組列表,使用命名元組。import csvfrom collections import namedtupleRec = 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 recsread_file("./data/file.csv")這可能是一些新手問題,但我就是這樣:) 我會很感激任何幫助!
1 回答

MMTTMM
TA貢獻1869條經驗 獲得超4個贊
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
添加回答
舉報
0/150
提交
取消