Python 如果值已存在,则更新计数器索引
嘿,伙计们,我需要你们的帮助,请不要生吃我。我的python技能充其量是业余的。我有一个传递给函数的排序值列表 id------小时 100000005 01 1000006601 1000006605 1000006605 100002460 12 100002460 12 10000246013 10000446712 10000446720 10007117005 100071170 12 100071170 12 100071170 14 因此,我的代码检查一个数组,看看该数组中是否存在id,如果不存在,则将id和Hrs添加到数组中并递增计数器。但是如果该id已经存在,那么如果Hrs已经存在,则检查该id。如果Hrs已经存在,则增加已添加的次数,如果不存在,则将其插入阵列。最后,代码必须打印出每个id出现最多的小时数。因此最终输出应该是 id------小时 10000005 01 01出现一次 10000006605出现两次 100002460 12出现两次 100004467 12出现一次 100004467 20出现一次 100071170 12出现两次 我还没有谈到处理最终输出的代码部分 我的代码是Python 如果值已存在,则更新计数器索引,python,counter,Python,Counter,嘿,伙计们,我需要你们的帮助,请不要生吃我。我的python技能充其量是业余的。我有一个传递给函数的排序值列表 id------小时 100000005 01 1000006601 1000006605 1000006605 100002460 12 100002460 12 10000246013 10000446712 10000446720 10007117005 100071170 12 100071170 12 100071170 14 因此,我的代码检查一个数组,看看该数组中是否存在
import sys
import datetime
counter = 0
oldercounter = 0
countarray = []
existarray = []
for line in sys.stdin:
data = line.strip().split("\t")
counter += 1
if len(data) != 2:
continue
userid,newHrs = data # data that is taken from the array
if userid not in existarray: # if the userid doesn't exist in the the exist array, insert that row of data into the array
existarray.append(userid)
existarray.append(newHrs)
countarray.insert(counter,int(1)) # insert one at that position
if userid in existarray: # if the id already exits
if newHrs in existarray: # check if the newhrs already exist in the array
countarray.insert(counter,counter +1) # update it number of times i
else: # if new hrs is not in exist array, the add it
existarray.append(newHrs)
countarray.insert(counter,int(1))
print existarray ,"\t",countarray
existarray[:] = []
countarray[:] = []
谢谢您的帮助。您可以将a与:
屈服
100000066 05 appears 2 time
100000005 01 appears 1 time
使用计数器,您不需要以与不存在的键不同的方式处理现有键
c[key] += 1
在任何一种情况下都将正确增加计数器
注意:在Python2.6中添加了。对于较旧版本的Python,可以使用
print('%d %02d appears %d time' % (key, hrs, freq))
相反。如果给定idi的hrs已经存在,我如何增加计数器。我将立即尝试此操作。嘿,伙计,我非常感谢你的帮助,但是当我运行程序时,我发现了这个错误。AttributeError:'module'对象没有属性'Counter'。计数器类是在Python 2.7中添加到集合模块的。对于较旧版本的Python,可以使用。嘿,伙计,我得到这个错误,找不到计数器类。考虑到代码太长,我把它放在了pastebin中。Python通常从上到下执行脚本中的语句。因此,必须将定义计数器类的类计数器代码放在countarray=Counter之前。
print('%d %02d appears %d time' % (key, hrs, freq))