【问题标题】:trying to increment the list value if key exits如果键存在,则尝试增加列表值
【发布时间】:2016-11-01 21:52:36
【问题描述】:
for line in open('transactions.dat','r'):
    item=line.rstrip('\n').split(',')
    custid=item[2]
    amt=item[4]
    if custid in cust:
        amt1=int(cust[custid])+int(amt)
        cust[custid]=amt1
    else:
        cust[custid]=[amt]

我正在尝试检查客户 ID 是否已经存在于字典中,然后只需在该客户中添加以前的金额和新金额。否则,将该金额添加到列表中的新位置。但我收到错误:

 Traceback (most recent call last):
File "<pyshell#74>", line 7, in <module>
amt1=int(cust[custid])+int(amt)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'                    

一些交易数据是这样的:

101300101,2016-09-03,376248582,1013,10.92

109400132,2016-09-03,391031719,1094,36.72

136100107,2016-09-03,391031719,1361,28.77

【问题讨论】:

  • cust[custid]=amt替换cust[custid]=[amt]?
  • 不,它不起作用。问题在我的代码的第 7 行
  • 第 7 行的错误是 Isamael 指出的错误的后果
  • 不,它不起作用。它给出了这个错误:amt1=int(cust[custid])+int(amt) TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
  • @Kam,它给你这个错误即使你做了我建议的改变?

标签: python dictionary


【解决方案1】:

您是否尝试过使用defaultdict?这会让你的工作更轻松。

from collections import defaultdict

cust = defaultdict(int)
for line in open('transactions.dat','r'):
    item=line.rstrip('\n').split(',')
    custid=item[2]
    amt=item[4]

    cust[custid] += float(amt)

您为什么尝试将amt 转换为int?看起来它不是您发布的示例行中的整数。如果你真的想使用整数,请将float(amt) 更改为int(float(amt))

【讨论】:

  • 我想做的是为同一个客户 ID 添加相似的金额,然后添加到列表中...而不是多次引用客户 ID
  • 我不清楚您要做什么。您是要为每个客户列出所有 amounts 的列表,还是为每个客户查找所有金额的总和?
  • 尝试为具有相同 ID 的客户添加金额。这样每个客户都可以查看总数
  • 那我的回答应该有效。如果 custid 没有退出,它会在字典中创建一个新的 custid,否则它将找到 amt 并将其添加到客户记录中。为什么你认为它不起作用?
  • 它有效,我试过只是其他部分有问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
  • 1970-01-01
  • 1970-01-01
  • 2015-06-08
  • 1970-01-01
  • 2015-05-03
  • 2023-03-23
相关资源
最近更新 更多