首页 > 编程语言 >Python计数:defaultdict和Counter

Python计数:defaultdict和Counter

时间:2024-09-15 14:02:30浏览次数:6  
标签:defaultdict nums Python Counter List int ans

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

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

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

标签:defaultdict,nums,Python,Counter,List,int,ans
From: https://www.cnblogs.com/faf4r/p/18415210

相关文章