计数器(Counter)! |7 s. p. R2 u7 v/ u/ T
dict的子类,计算可hash的对象2 H0 z, r4 c" n! @
请点击Counter2 X) T4 ~, b: D% M/ S+ _: K
Counter()主要功能:可以支持方便、快速的计数,将元素数量统计,然后计数并返回一个字典,键为元素,值为元素个数。+ S2 S$ v8 ^5 S1 N9 g6 E' ^
- from collections import Counter" A6 t" j, T0 I/ t2 z
9 ~# _) p' D0 {& {/ o& {- list1 = ["a", "a", "a", "b", "c", "c", "f", "g", "g", "g", "f"]2 v6 L$ [, P+ i; _* A7 l0 [; S
- dic = Counter(list1)
/ C" r9 _) v r m% { - print(dic)
1 l8 s7 S# ~9 L8 u0 P - #结果:次数是从高到低的
5 b/ V# Z1 o8 @# G - #Counter({'a': 3, 'g': 3, 'c': 2, 'f': 2, 'b': 1})1 ?, l" n3 s: o% M3 {
; G; w( d X V3 i8 H- print(dict(dic))
8 A& i/ D" i( z( K- O' Z - #结果:按字母顺序排序的
" x9 y( L$ S- } - #{'a': 3, 'b': 1, 'c': 2, 'f': 2, 'g': 3}
, Z6 A+ J9 [6 A$ { u - " V: v# r. [4 q" J0 |
- print(dic.items()) #dic.items()获取字典的key和value
. M8 C$ t3 B# G) ~. g3 H! f - #结果:按字母顺序排序的
* \, `+ R. U/ y! D& R5 T L% @ - #dict_items([('a', 3), ('b', 1), ('c', 2), ('f', 2), ('g', 3)])
1 V' s l$ ]# n - " f' c% o' n. l R; `
- print(dic.keys())
* p5 {8 g" g- K5 C - #结果:
9 L) l9 G) ?+ ` - #dict_keys(['a', 'b', 'c', 'f', 'g'])7 k5 f% ?" E/ u- _
, ~: w! y: d+ X$ A1 t' p* n- print(dic.values())
( l+ N5 T6 k3 |6 R/ F9 Q - #结果:
. K$ F( I: D% ], k - #dict_values([3, 1, 2, 2, 3])
j7 u1 t9 e8 R4 S - & V! `5 K% \5 E2 k- \
- print(sorted(dic.items(), key=lambda s: (-s[1])))# a1 _) o+ m* q& y8 T+ w$ e
- #结果:按统计次数降序排序
5 @% `( M' g$ F! M3 |. \* Z8 U n. k - #[('a', 3), ('g', 3), ('c', 2), ('f', 2), ('b', 1)]
$ W* O* k& B! E7 o* \, a
$ O+ h% M) c2 [& f; d, L6 d8 [8 f- for i, v in dic.items():7 H% s' S$ ]) Z, ^
- if v == 1:1 ~9 [8 Y+ F3 k( b' ~7 I
- print(i); n3 P' h2 ?' a- U2 g+ d# y
- #结果:
# a# _ x7 K5 d - #b
$ ]3 S2 z) R# _
复制代码