![](/img/trans.png)
[英]Check if value already exists within list of dictionaries and if it does update the counter
[英]updating counter index if the value already exists
大家好,我需要您的幫助,請不要生我的肉。 我的python技能充其量是業余的。 我有一個傳遞給函數的排序值列表。
id ------------ 小時
100000005 01
100000066 01
100000066 05
100000066 05
100002460 12
100002460 12
100002460 13
100004467 12
100004467 20
100071170 05
100071170 12
100071170 12
100071170 14
所以我的代碼檢查一個數組以查看該數組中是否存在id,如果不存在,則將id和Hrs添加到數組中並增加計數器。 但是,如果該ID已經存在,則檢查該Hrs是否已經存在。 如果Hrs已經存在,則增加它被添加的次數,如果不存在,則將其插入到數組中。 最后,代碼將必須打印出每個ID最多出現的Hrs。 所以最后的輸出應該是
id ----------- 小時
100000005 01 (01-出現一次)
100000066 05 (兩次出現05)
100002460 12 (兩次出現12次)
100004467 12 (一次出現12次)
100004467 20 (一次出現20次)
100071170 12 (兩次出現12次)
我還沒有處理最終輸出的代碼部分。
我的代碼是
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[:] = []
謝謝你的幫助。
你可以使用一個collections.defaultdict與collections.Counter :
import collections
c = collections.defaultdict(collections.Counter)
c[100000005][3] += 1
c[100000066][4] += 1
c[100000066][5] += 1
c[100000066][5] += 1
for key, counter in c.iteritems():
for hrs, freq in counter.most_common(1):
print('{0} {1:02d} appears {2} time'.format(key, hrs, freq))
產量
100000066 05 appears 2 time
100000005 01 appears 1 time
使用Counter
,您不需要像處理不存在的密鑰那樣處理現有的密鑰。
c[key] += 1
無論哪種情況,都將正確增加Counter
。
注意: format
字符串方法是在Python 2.6中添加的。 對於舊版本的Python,您可以使用
print('%d %02d appears %d time' % (key, hrs, freq))
代替。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.