2024-09-15 14:05阅读: 22评论: 0推荐: 0

Python计数:defaultdict和Counter

使用Python内置的defaultdict和Counter能方便的实现计数等操作

题目:3289. 数字小镇中的捣蛋鬼

copy
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
from typing import List from collections import defaultdict, Counter class Solution: def getSneakyNumbers(self, nums: List[int]) -> List[int]: counter = Counter(nums) ans = [] for key in counter: if counter[key] > 1: ans.append(key) return ans def getSneakyNumbers(self, nums: List[int]) -> List[int]: ans = [] d = defaultdict(int) # 键不存在时调用int()返回0 for i in nums: d[i] += 1 if d[i] > 1: ans.append(i) return ans

本文作者:faf4r

本文链接:https://www.cnblogs.com/faf4r/p/18415210

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   faf4r  阅读(22)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起