2016-02-21 29 views
0

我想每次在我掃描的列表中出現特定值時都要保留一個計數器。通過遞增該值來修改dictionary(或defaultdictionary)中的現有值

例如: 列表:喜歡

[(a, 0.2), (b, 1), (a, 0.2), (a, 1)] 

我的字典,可以顯示以下內容:

mydict = {"a": (# val below 1, # val equal to 1), ...}

因此: mydict = {"a": (2, 1), "b" :(0, 1)}

是有辦法用默認字典或普通字典來做到這一點?

對於每個我看到低於或等於1的值,我是否應該這樣做: mydict[mydict["a"]+1]

+0

我不明白是怎麼預期的輸出與輸入 –

+0

0.2和0.2都獲得因此「a」中的第一個值:2,1是2.另一個a 1等於1,所以元組「a」:2,1的第二個值是1.這有幫助嗎? – amc

回答

2

好的,假設輸入類型是一個數組數組,並且可以將結果作爲數組存儲在字典中,那麼可以這樣做。

# Define list of numbers 
lettersNumbersList = [["a", 0.2], ["b", 1], ["a", 0.2], ["a", 1]] 

# Here is the dictionary you will populate. 
numberOccurences = {} 

# This function is used to increment the numbers depending on if they are less 
# than or greater than one. 
def incrementNumber(letter, number): 

    countingArray = numberOccurences[letter] 

    if number < 1: 
     countingArray[0] = countingArray[0] + 1 
    elif number >= 1: 
     countingArray[1] = countingArray[1] + 1 

    return(countingArray) 

# Loops through all of the list, gets the number and letter from it. If the letter 
# is already in the dictionary then increments the counters. Otherwise starts 
# both from zero. 
for item in lettersNumbersList: 

    letter = item[0] 
    number = item[1] 

    if letter in numberOccurences: 
     numberOccurences[letter] = incrementNumber(letter, number) 

    else: 
     numberOccurences[letter] = [0, 0] 
     numberOccurences[letter] = incrementNumber(letter, number) 

print(numberOccurences) 
+0

這個效果很好!非常感謝你!!真的很棒。 – amc

1

這應該是比其他解決方案(也很乾淨,Python的恕我直言)快:

mylist = [("a", 0.2), ("a", 0.9), ("b", 1), ("a", 1)] 

mydict = dict(mylist) 

for k in mydict.keys(): 
    mydict[k] = (len([t for t in mylist if t[0]==k and t[1]<1]), 
       len([t for t in mylist if t[0]==k and t[1]==1])) 

# >>> mydict 
# {'a': (2, 1), 'b': (0, 1)}