我正在處理 python 代碼,但出現(xiàn)此錯(cuò)誤:“TypeError: new () missing 3 required positional arguments: 'name', 'freq', and 'gen'”我正在導(dǎo)入一個(gè) csv 文件來(lái)創(chuàng)建一個(gè)元組列表,使用命名元組。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")這可能是一些新手問(wèn)題,但我就是這樣:) 我會(huì)很感激任何幫助!
1 回答

MMTTMM
TA貢獻(xiàn)1869條經(jīng)驗(yàn) 獲得超4個(gè)贊
line
是一個(gè)元組。當(dāng)您調(diào)用Rec(line)
時(shí),整個(gè)元組被解釋為year
參數(shù)(缺少其他三個(gè)參數(shù),因此出現(xiàn)錯(cuò)誤)。
要解決此問(wèn)題,請(qǐng)更改
recs = Rec(line)
至
recs = Rec(*line)
或者
recs = Rec._make(line)
https://docs.python.org/2/library/collections.html#collections.somenamedtuple._make
添加回答
舉報(bào)
0/150
提交
取消