我正在尝试使用 namedtuple
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)
看来我有问题,我如何使用位置参数。
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
请您参考如下方法:
此错误消息表示您没有向 Stock() 构造函数传递足够的参数。您的元组有 3 个元素,因此您需要将 3 个参数传递给构造函数。
但是在这一行中:
for rec in records:
records 是文件中的一行。因此 rec 只是单个字符。
提示:for rec in records.split("")
