python - 类型错误 : __new__() missing 2 required positional arguments: 'shares' and 'price'

标签 python

我正在尝试使用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/

相关文章:

python - 使用python进行矩阵运算

python - 如何连接两个具有重复列名的数据框?

python - 具有时变狄利克雷边界条件的非稳态扩散-平流方程

python - 解包单值元​​组的可读约定

python - 基于 Django 类的 View - 将所有代码放在 urls.py 中是一种不好的风格吗?

python - 在 Python 中解析大型 XML 文件

python - Python 3.x 中的字典采样

python - FFMPEG 仅在写入管道时引发异常

python - 定义线之间的距离

python - 从 Pandas Series 中选择行,其中行是数组