我正在尝试使用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发布于 2017-07-25 16:43:50
这个错误消息意味着您没有向Stock()构造函数传递足够的参数。您的元组有3个元素,所以您需要将3个参数传递给构造函数。
但在这一行中:
for rec in records:records是文件中的一行。因此,rec只是一个字符。
提示:for rec in records.split(" ")
https://stackoverflow.com/questions/45297862
复制相似问题