英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论