Python Forum
How to get unique entries in a list and the count of occurrence
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to get unique entries in a list and the count of occurrence
#1
Hello. I have some data such as this.

aaa
bbb
ccc
aaa
ccc
ddd
fff
aaa
ccc
aaa

I know using the set will give the unique values but what i need is the unique values and the count. for example:

aaa 4
bbb 1
ccc 3
ddd 1
Reply
#2
Batteries included ...

from collections import Counter


your_input = """aaa
bbb
ccc
aaa
ccc
ddd
fff
aaa
ccc
aaa"""

sequence = your_input.strip().split()
counter = Counter(sequence)

print(counter.most_common(5))
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
Thanks a lot.
Reply
#4
Or if you want to know how to do it:
your_input = """aaa
bbb
ccc
aaa
ccc
ddd
fff
aaa
ccc
aaa"""

counts = {}
for entry in your_input.strip().split()
    counts[entry] = counts.get(entry, 0) + 1
Reply
#5
from collections import Counter
input = ['a', 'a', 'b', 'b', 'b']
c = Counter( input )

print( c.items() ) .
Reply
#6
If all you want to do is find the counts (and not do any further processing in a Python script), then if you're on UNIX, you don't need Python at all. Command line tools will do the job:

Output:
$ cat << EOF | sort | uniq -c aaa bbb ccc aaa ccc ddd fff aaa ccc aaa EOF 4 aaa 1 bbb 3 ccc 1 ddd 1 fff
Obviously you can read from a file if you needed to, but I've used a here document to pass the input to cat. uniq's -c option provides the counts but the program looks at adjacent lines only to filter out duplicates, so sort is necessary to put them next to each other.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sample random, unique string pairs from a list without repetitions walterwhite 1 401 Nov-19-2023, 10:07 PM
Last Post: deanhystad
  Function to count words in a list up to and including Sam Oldman45 15 6,410 Sep-08-2023, 01:10 PM
Last Post: Pedroski55
  Row Count and coloumn count Yegor123 4 1,268 Oct-18-2022, 03:52 AM
Last Post: Yegor123
  For Word, Count in List (Counts.Items()) new_coder_231013 6 2,497 Jul-21-2022, 02:51 PM
Last Post: new_coder_231013
  df column mean and count of unique SriRajesh 0 1,092 May-07-2022, 08:19 AM
Last Post: SriRajesh
  How to efficiently average same entries of lists in a list xquad 5 2,070 Dec-17-2021, 04:44 PM
Last Post: xquad
  count item in list korenron 8 3,373 Aug-18-2021, 06:40 AM
Last Post: naughtyCat
  Selecting the first occurrence of a duplicate knight2000 8 5,094 May-25-2021, 01:37 AM
Last Post: knight2000
  list.count does not appear to function Oldman45 7 3,840 Mar-16-2021, 04:25 PM
Last Post: Oldman45
  List of error codes to find (and count) in all files in a directory tester_V 8 3,585 Dec-11-2020, 07:07 PM
Last Post: tester_V

Forum Jump:

User Panel Messages

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