我正在尝试使用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 record.split("")
关于python - 类型错误 : __new__() missing 2 required positional arguments: 'shares' and 'price' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45297862/