失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python统计字典中元素个数_Python计数器 | collections.Counter

python统计字典中元素个数_Python计数器 | collections.Counter

时间:2019-04-04 05:04:07

相关推荐

python统计字典中元素个数_Python计数器 | collections.Counter

问题:给定序列,统计所有元素出现的次数

法一 : seq.count()

seq = 'abcdbabaecccdbb' #待统计序列

#先变成集合得到seq中的所有元素,避免重复遍历

set_seq = set(seq)

rst = []

for item in set_seq:

rst.append((item,seq.count(item))) #添加元素及出现个数

#输出结果,[('a', 3), ('e', 1), ('b', 5), ('c', 4), ('d', 2)]

print(rst)

法二:使用字典dict

seq='abcdbabaecccdbb' #待统计序列

dict = {}

for item in seq: #遍历str

if item not in dict: #第一次出现,赋初值1

dict[item] = 1

else: #出现次数加一

dict[item] += 1

#得到结果 {'a': 3, 'b': 5, 'c': 4, 'd': 2, 'e': 1}

print(dict)

法三:使用内置模块collections中的Counter类

'''Counter是用于计算可哈希对象的dict子类,

其中元素存储在字典键中,计数存储在字典值中

不可哈希: 列表,集合,字典

可哈希: 数值,元组,字符串,布尔类型'''

from collections import Counter

seq ='abcdbabaecccdbb' #待统计序列

'''Counter()统计每个元素出现次数'''

counter = Counter(seq)

#counter --> Counter({'b': 5, 'c': 4, 'a': 3, 'd': 2, 'e': 1})

print(counter)

'''most_common(n)统计出现次数前n位的元素'''

most = counter.most_common()

#most --> [('b', 5), ('c', 4), ('a', 3), ('d', 2), ('e', 1)]

'''可以指定输出个数和排序方式'''

most_one = counter.most_common(1)

print(most_one) #most_one --> [('b', 5)]

#根据元素大小升序排序

most.sort(key = lambda item:item[0])

print(most) #most --> [('a', 3), ('b', 5), ('c', 4), ('d', 2), ('e', 1)]

#根据出现次数降序排序

most.sort(key = lambda item:item[-1],reverse = True)

print(most) #most --> [('b', 5), ('c', 4), ('a', 3), ('d', 2), ('e', 1)]

LeetCode | 347. 前K个高频元素

题目描述 :给定一个非空的整数数组,返回其中出现频率前 k 高的元素。

示例 1:

输入: nums = [1,1,1,2,2,3], k = 2

输出: [1,2]

示例 2:

输入: nums = [1], k = 1

输出: [1]

from collections import Counter

class Solution(object):

def topKFrequent(self, nums, k):

"""

:type nums: List[int]

:type k: int

:rtype: List[int]

"""

cnt = Counter(nums)

top_k = cnt.most_common(k) #返回nums中前k个高频元素

return [rst[0] for rst in top_k] #返回结果

result = Solution()

nums = [1,2,3,2,3,4,3,1,2,4,4,5,4,2,2]

#先看一下nums的统计信息

print(Counter(nums)) # Counter({2: 5, 4: 4, 3: 3, 1: 2, 5: 1})

#前k个高频元素

print(result.topKFrequent(nums,3)) #[2, 4, 3]

LeetCode | 451. 根据字符出现频率排序

题目描述 :给定一个字符串,请将字符串里的字符按照出现的频率降序排列

示例 1:

输入:

"tree"

输出:

"eert"

解释:

'e'出现两次,'r'和't'都只出现一次。

因此'e'必须出现在'r'和't'之前。此外,"eetr"也是一个有效的答案。

示例 2:

输入:

"cccaaa"

输出:

"cccaaa"

解释:

'c'和'a'都出现三次。此外,"aaaccc"也是有效的答案。

注意"cacaca"是不正确的,因为相同的字母必须放在一起。

示例 3:

输入:

"Aabb"

输出:

"bbAa"

解释:

此外,"bbaA"也是一个有效的答案,但"Aabb"是不正确的。

注意'A'和'a'被认为是两种不同的字符。

from collections import Counter

class Solution(object):

def frequencySort(self, s):

"""

:type s: str

:rtype: str

"""

rst = ''

cnt = Counter(s)

most = cnt.most_common()

#将字符串里的字符按照出现的频率降序排列

most.sort(key = lambda x: x[-1],reverse = True)

for element,count in most: #遍历

rst += element * count #element --> 元素

return rst #count --> 出现次数

result = Solution()

print(result.frequencySort("tree")) #eetr

print(result.frequencySort("bbAa")) #bbAa

LeetCode | 136. 只出现一次的数字

题目描述:给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

示例 1:

输入: [2,2,1]

输出: 1

示例 2:

输入: [4,1,2,1,2]

输出: 4

from collections import Counter

class Solution:

def singleNumber(self, nums):

"""

:type nums: List[int]

:rtype: int

"""

cnt = Counter(nums)

s = cnt.most_common(len(nums)) #返回(值,次数),并按出现次数排序

return s[-1][0] #出现一次的元素在最后

''' 方法二:

^ 异或-->自身异或得0, 1^1 --> 0. 与0异或得到自身, 123^0 --> 123

异或满足交换律 --> 1^2^1 == 1^1^2 --> 2.

2^3^4^2^3 == 2^2^3^3^4 --> 4

因为出现一次的元素只有一个,所以对nums中所有元素进行异或即可得到结果

rst = 0

for num in nums:

rst ^= num

return rst

'''

result = Solution()

print(result.singleNumber([4,1,2,1,2])) #4

统计哈姆雷特中出现次数最多的20个词

from collections import Counter

import re

#正则表达式分割单词并转小写

words = re.findall(r'\w+', open('hamlet.txt').read().lower())

count = Counter(words)

most_20 = count.most_common(20)

print('序号 单词 出现次数')

for idx,(word,cnt) in enumerate(most_20,1):

print(' {0:<8}{1:<10}{2:>2}'.format(idx,word,cnt))

'''输出结果

序号 单词 出现次数

1 the 1143

2 and 966

3 to 762

4 of 669

5 i 631

6 you 554

7 a 546

8 my 514

9 hamlet 471

10 in 451

11 it 419

12 that 407

13 is 358

14 not 315

15 lord 311

16 this 297

17 his 296

18 but 271

19 with 268

20 for 252

'''

如果觉得《python统计字典中元素个数_Python计数器 | collections.Counter》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。