简体   繁体   中英

Find the count of the occurrences of an integer in an array in Python

I have seen this and this . I was wondering if I could do it without using libraries like collection, but with a simple loop structure. Can I do this in Python?

void printRepeating(int arr[], int size)
{
  int *count = (int *)calloc(sizeof(int), (size - 2));
  int i;

  printf(" Repeating elements are ");
  for(i = 0; i < size; i++)
  {  
    if(count[arr[i]] == 1)
      printf(" %d ", arr[i]);
    else
     count[arr[i]]++;
  }    
} 

I tried doing this -

a=[1,2,3,2,4,3,1,7,4,3];
b=[];
for i in a:
        b[i]=b[i]+1;

But I get

IndexError: list index out of range

Is there a way around it?

Using a dict (Python's built-in hash map type) will be the simplest:

a = [1,2,3,2,4,3,1,7,4,3]
b = {}
for i in a:
    # get(key, default) falls back to default if key is not present
    b[i] = b.get(i, 0) + 1

> b
{1: 2, 2: 2, 3: 3, 4: 2, 7: 1}
> b[3]
3

Welcome to Python world, you C developer! ;) You can drop the semicolons here.

Your b here is a Python list with 0 elements, you cannot get or set elements inside it this way: b[i] if an element with index i does not exist already.

But there are plenty of ways to do what you want. If you really don't want to use built-in libraries, you can try this way (should produce the exact same output as your C code):

a = [1,2,3,2,4,3,1,7,4,3]
print("Repeating elements are")
for i in a:
    if a.count(i) > 1:
        print(i)

But a collections.Counter is the best way to do it, it is built-in so why not use it ?

from collections import Counter
a = [1,2,3,2,4,3,1,7,4,3]
counter = Counter(a)
print(counter.most_common())

If I understood you correctly, you are creating b as a list to count the occurrences of each of the numbers in a . That way, you can create a dictionary that might be easier:

a=[1,2,3,2,4,3,1,7,4,3]
b={}
for i in a:
    if i in b:
        b[i]+=1
    else:
        b[i]=1

And then go through the dictionary to check for repeats.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM