random_user_0891
random_user_0891

Reputation: 2071

python count occurrence of list items

I'm new to Python and I'm stuck trying to figure out how to count how many times a number shows up in a list. The output I'm looking for is something like this "7 occurred 2 times, 4 occurred 1 time" but the problem I'm running into is that I'm printing output for each my_integer. So if I enter 7, 7, 4 as input I get "7 occurred 2 times, 7 occurred 2 times, 4 occurred 1 time" I was thinking of writing a method to check for uniqueness of a number after count has been returned.

integers = input("Enter integers between 1 and 100: ")
split_integers = integers.split()
integer_list = [eval(x) for x in split_integers]

for my_integer in integer_list:
    print(integer_list.count(my_integer))

Upvotes: 2

Views: 342

Answers (5)

Sohaib Farooqi
Sohaib Farooqi

Reputation: 5676

You can use itertools.groupby to generate a dict of element and number of times it appears in the list. The input list to groupby should be sorted(either in ascending or descending).

>>> from itertools import groupby
>>> l = [1,2,2,1,3,3,3,3,4,5,6,6,6]
>>> {k:len(list(v)) for k,v in groupby(sorted(l))}

This will output

>>> {1: 2, 2: 2, 3: 4, 4: 1, 5: 1, 6: 3}

Or you can use list comprehension to produce a list of tuples and then pass it to dict constructor. This will also yield same result

>>> dict((k,len(list(v))) for k,v in groupby(sorted(l)))
>>> {1: 2, 2: 2, 3: 4, 4: 1, 5: 1, 6: 3}

Upvotes: 2

RoadRunner
RoadRunner

Reputation: 26335

Firstly, you don't need to use eval() in this line:

 integer_list = [eval(x) for x in split_integers]

you can simply cast int() here.

Furthermore, since your just counting numbers, you don't even need to convert them to integers to begin with. The conversion would only be necessary if you needed to do some computation with these integers, but since your just counting unique ones, keeping them as strings works fine here.

Secondly, if you want to count unique items, you can use collections.Counter() for this:

from collections import Counter

integers = input("Enter integers between 1 and 100: ")
split_integers = integers.split()

counts = Counter(split_integers)
for k, v in counts.items():
    print(k, 'occurred', v, 'times')

Which works as follows:

Enter integers between 1 and 100: 7 7 4 7 4
7 occurred 3 times
4 occurred 2 times

Counter() is basically a subclass of dict for counting objects. It stores elements in a dictionary where the elements are stored as keys and their counts as values. This allows you to count unique items and store how many times they occur.

Upvotes: 5

oldlodestone
oldlodestone

Reputation: 52

No module imports:

b = []                               #addition 1
for my_integer in integer_list:
    if my_integer in b:
        print (value, "occurs", integer_list.count(my_integer))
        b.append(my_integer)

or

while len(a) > 0:
   value = a[0]
   count = a.count(value)
   print (value, "occurs", count)
   for i in range(count):
      a.remove(value)

Upvotes: 0

kiyah
kiyah

Reputation: 1528

You can use set().

for my_integer in set(integer_list):
    count = integer_list.count(my_integer)
    tmp = "{} occurred {} time".format(my_integer, count)
    if count > 1:
        tmp += "s"
    print(tmp)

For integer_list = [7, 7, 4], it should print out

4 occurred 1 time
7 occurred 2 times

Why does it print the number 4 first before 7? Because set() automatically sorts the array. Learn more about it here.

Upvotes: 2

iBug
iBug

Reputation: 37317

You can use a dictionary:

integers = input("Enter integers between 1 and 100: ")
split_integers = integers.split()
integer_list = [eval(x) for x in split_integers]

counts = {}
for my_integer in integer_list:
    try:
        counts[my_integer] += 1
    except KeyError:
        counts[my_integer] = 1

for k in counts:
    print('Integer {} occurred {} times'.format(k, counts[k]))

Upvotes: 1

Related Questions