-2

I have a list of random numbers in no specific order. Is there a way to count the number of times each number can be found in the list, and create a new list with these counts using a for loop? So not using an existing Python function. So, for example I have the list [9,18,13,9,6,6,16,6,17,10,15,16,13,11,13,8,20,6,18,11]. The output I want to have is [2,2,3,2,4 etc.].

A code I currently have is:

def countlisting(numberlist):
    the_count = 0
    q = 0
    listofcount = []
    for i in range(len(numberlist)):
        if numberlist[i] == numberlist[q]:
            the_count += 1
            listofcount.append(the_count)
            q += 1
    return listofcount

the_numberlist = [9,18,13,9,6,6,16,6,17,10,15,16,13,11,13,8,20,6,18,11]
print(countlisting(the_numberlist))  

August
  • 27
  • 6

3 Answers3

1

You can use collections.Counter for this:

from collections import Counter

the_numberlist = [9,18,13,9,6,6,16,6,17,10,15,16,13,11,13,8,20,6,18,11]
c = Counter(the_numberlist)
print(list(c.values()))

Output:

[2, 2, 3, 4, 2, 1, 1, 1, 2, 1, 1]
Will Da Silva
  • 6,386
  • 2
  • 27
  • 52
1

You can use collections.Counter and get values from dict like below:

>>> from collections import Counter
>>> the_numberlist = [9,18,13,9,6,6,16,6,17,10,15,16,13,11,13,8,20,6,18,11]
>>> list(Counter(the_numberlist).values())
[2, 2, 3, 4, 2, 1, 1, 1, 2, 1, 1]



# for more explanation
>>> Counter(the_numberlist)
Counter({9: 2,
         18: 2,
         13: 3,
         6: 4,
         16: 2,
         17: 1,
         10: 1,
         15: 1,
         11: 2,
         8: 1,
         20: 1})

You can implement this counter yourself

>>> dct_cnt = {}
>>> for num in the_numberlist:
...    dct_cnt[num] = dct_cnt.get(num, 0) + 1
    
>>> dct_cnt
{9: 2, 18: 2, 13: 3, 6: 4, 16: 2, 17: 1, 10: 1, 15: 1, 11: 2, 8: 1, 20: 1}

>>> list(dct_cnt.values())
[2, 2, 3, 4, 2, 1, 1, 1, 2, 1, 1]
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
0
sum=0
list1=[]
the_numberlist = [9,18,13,9,6,6,16,6,17,10,15,16,13,11,13,8,20,6,18,11]
for i in range(len(the_numberlist)):
    for j in range(len(the_numberlist)):
        if the_numberlist[0]==the_numberlist[j]:
         sum+=1
    if len(the_numberlist)!=0:
      remove_element=the_numberlist[0]
    else:
        break
    while remove_element in the_numberlist:
        the_numberlist.remove(remove_element)
    list1.append(sum)
    sum=0
print(list1)

#output: [2, 2, 3, 4, 2, 1, 1, 1, 2, 1, 1]

I did my best for don`t use the function

Good luck