通过递增该值来修改字典(或defaultdictionary)中的现有值

时间:2016-02-21 17:20:37

标签: python dictionary count defaultdict

我想在我扫描的列表中每次出现特定值时都保留一个计数器。

例如: 列表:

[(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)}

有没有办法用默认字典或普通字典做到这一点?

我应该这样做: mydict[mydict["a"]+1]我看到的每个值是低于还是等于1?

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

这应该比其他解决方案更快(同样,非常干净和Pythonic恕我直言):

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)}