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

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

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

问题

这是我的实际代码:

  1. def uniqueOccurrence(item1, item2, item3):
  2. d = {}
  3. for i in d:
  4. if i in d:
  5. d[i] = d[i] + 1
  6. else:
  7. d[i] = 1
  8. return d
  9. def main():
  10. list1 = [1]
  11. list2 = [1,2]
  12. list3 = [1,2,3]
  13. print(uniqueOccurrence(list1, list2, list3))
  14. if __name__ == "__main__":
  15. 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

  1. def uniqueOccurrence(item1, item2, item3):
  2. d = {}
  3. for i in d:
  4. if i in d:
  5. d[i] = d[i] + 1
  6. else:
  7. d[i] = 1
  8. return d
  9. def main():
  10. list1 = [1]
  11. list2 = [1,2]
  12. list3 = [1,2,3]
  13. print(uniqueOccurrence(list1, list2, list3))
  14. if __name__ == "__main__":
  15. main()

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

but is returning an empty dictionary
{}

答案1

得分: 1

以下是翻译好的部分:

  1. 你不在函数中使用你的输入参数你可以这样做
  2. def count_elements(*lists):
  3. element_count = {}
  4. for lst in lists:
  5. for element in lst:
  6. if element in element_count:
  7. element_count[element] += 1
  8. else:
  9. element_count[element] = 1
  10. return element_count
  11. count_elements(list1, list2, list3)
  12. 或者使用 [Counter][1]
  13. from collections import Counter
  14. def count_elements(*lists):
  15. element_count = Counter()
  16. for lst in lists:
  17. element_count.update(lst)
  18. return element_count
  19. count_elements(list1, list2, list3)
  20. [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:

  1. def count_elements(*lists):
  2. element_count = {}
  3. for lst in lists:
  4. for element in lst:
  5. if element in element_count:
  6. element_count[element] += 1
  7. else:
  8. element_count[element] = 1
  9. return element_count
  10. count_elements(list1, list2, list3)

Or use a Counter:

  1. from collections import Counter
  2. def count_elements(*lists):
  3. element_count = Counter()
  4. for lst in lists:
  5. element_count.update(lst)
  6. return element_count
  7. 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:

确定