How can I make a function with a dictionary of occurrences from list I set later?

huangapple go评论66阅读模式
英文:

How can I make a function with a dictionary of occurrences from list I set later?

问题

这是我的实际代码:

def uniqueOccurrence(item1, item2, item3):
    d = {}
    for i in d:
        if i in d:
            d[i] = d[i] + 1
        else:
            d[i] = 1
    return d
    
def main():
    list1 = [1]
    list2 = [1,2]
    list3 = [1,2,3]
    
    print(uniqueOccurrence(list1, list2, list3))
    
if __name__ == "__main__":
    main()

应该返回类似这样的结果:
{1: 3, 2: 2, 3: 1}

但实际上返回一个空字典:
{}

英文:

I have a set of functions that are meant to set a dictionary with the key being the character that occurs in the lists and the items being the number of occurrences but when I run the code the dictionary is empty.

This is my actual code

def uniqueOccurrence(item1, item2, item3):
    d = {}
    for i in d:
        if i in d:
            d[i] = d[i] + 1
        else:
            d[i] = 1
    return d
    
def main():
    list1 = [1]
    list2 = [1,2]
    list3 = [1,2,3]
    
    print(uniqueOccurrence(list1, list2, list3))
    
if __name__ == "__main__":
    main()

It is supposed to return something like this
{1: 3, 2: 2, 3: 1}

but is returning an empty dictionary
{}

答案1

得分: 1

以下是翻译好的部分:

你不在函数中使用你的输入参数你可以这样做

def count_elements(*lists):
    element_count = {}
    for lst in lists:
        for element in lst:
            if element in element_count:
                element_count[element] += 1
            else:
                element_count[element] = 1
    return element_count

count_elements(list1, list2, list3)


或者使用 [Counter][1]

from collections import Counter

def count_elements(*lists):
    element_count = Counter()
    for lst in lists:
        element_count.update(lst)
    return element_count

count_elements(list1, list2, list3)

[1]: https://docs.python.org/3/library/collections.html#collections.Counter
英文:

You do not use your input parameters in the function, you can do it like this:

def count_elements(*lists):
    element_count = {}
    for lst in lists:
        for element in lst:
            if element in element_count:
                element_count[element] += 1
            else:
                element_count[element] = 1
    return element_count

count_elements(list1, list2, list3)

Or use a Counter:

from collections import Counter

def count_elements(*lists):
    element_count = Counter()
    for lst in lists:
        element_count.update(lst)
    return element_count

count_elements(list1, list2, list3)

huangapple
  • 本文由 发表于 2023年2月24日 08:43:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75551673.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定