Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Occurence
#4
(Nov-08-2019, 08:18 AM)perfringo Wrote: For counting hashable objects there is built-in collections.Counter.

This enables counting and representing results in different ways:

>>> from collections import Counter
>>> nums = [1, 2, 3, 1, 2, 5, 6, 7, 7]
>>> counts = Counter(nums)
>>> counts
Counter({1: 2, 2: 2, 7: 2, 3: 1, 5: 1, 6: 1})
Print out counted items with their occurrance (sorted):

>>> print(*(f'{num}:{count}' for num, count in counts.most_common()), sep='\n')
1:2
2:2
7:2
3:1
5:1
6:1
How many values were counted:

>>> sum(counts.values())
9
How many different objects were counted:

>>> len(counts)
6
All values in sorted order:

>>> print(*counts.elements())
1 1 2 2 3 5 6 7 7
>>> list(counts.elements())
[1, 1, 2, 2, 3, 5, 6, 7, 7]
It doesn't throw an error if asked for object (key) not present, it just 'nicely' says that count is zero:

>>> counts[1]
2
>>> counts[100]
0
Reply


Messages In This Thread
Occurence - by Adem - Nov-07-2019, 10:29 PM
RE: Occurence - by Gribouillis - Nov-07-2019, 10:48 PM
RE: Occurence - by perfringo - Nov-08-2019, 08:18 AM
RE: Occurence - by Adem - Nov-08-2019, 03:17 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Thumbs Up [SOLVED] Find last occurence of pattern in text file? Winfried 4 4,412 Aug-13-2021, 08:21 PM
Last Post: Winfried
  Delete minimum occurence in a string RavCOder 10 3,960 Nov-12-2019, 01:08 PM
Last Post: RavCOder

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020