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
'我'''記錄'是一條線,不是?既然你循環它,'rec'是該行中的單個字符。不知道你認爲你把這條線分成不同的值。 – deceze
您一次只將一條記錄提供給'compute_cost',但'compute_cost'需要一個可迭代的記錄。您已經忘記了哪些代碼負責迭代記錄。 – user2357112
是的,那麼我應該改變什麼? –