2017-07-25 85 views
2

我想使用namedtuple類型錯誤:__new __()缺少2個所需的位置參數:「股」和「價格」

from collections import namedtuple 
Stock = namedtuple('Stock', ['name', 'shares', 'price']) 

def compute_cost(records): 
    total = 0.0 
    for rec in records: 
     s = Stock(*rec) 
     total += s.shares * s.price 
    return total 

with open('r.txt') as f: 
    content = f.readlines() 
    content = [x.strip() for x in content] 
    for i in content: 
     p = compute_cost(i) 
    print (p) 

看來,我有問題,我的方式如何笏使用posicional參數。

File "b74.py", line 15, in <module> 
    p = compute_cost(i) 
    File "b74.py", line 7, in compute_cost 
    s = Stock(*rec) 
TypeError: __new__() missing 2 required positional arguments: 'shares' and 'price' 

這裏來我的文本文件

hmf Kiza 100 2.33 
piz Miki 999 0.75 
air Dush 500 8.50 
+2

'我'''記錄'是一條線,不是?既然你循環它,'rec'是該行中的單個字符。不知道你認爲你把這條線分成不同的值。 – deceze

+2

您一次只將一條記錄提供給'compute_cost',但'compute_cost'需要一個可迭代的記錄。您已經忘記了哪些代碼負責迭代記錄。 – user2357112

+0

是的,那麼我應該改變什麼? –

回答

2

此錯誤消息意味着你沒有足夠的傳遞參數的構造函數Stock()。你的元組有3個元素,所以你需要傳遞3個參數給構造函數。

但在這行:

for rec in records: 

records是在文件中一行。因此rec只是單個字符。

提示:for rec in records.split(" ")

相關問題