简体   繁体   English

在 Python 中查找数组中整数出现的次数

[英]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?我可以在 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:使用dict (Python 的内置哈希映射类型)将是最简单的:

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!欢迎来到 Python 世界,你是 C 开发者! ;) 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.您在这里的b是一个包含 0 个元素的 Python 列表,您不能以这种方式在其中获取或设置元素: b[i]如果索引为 i 的元素尚不存在。

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):如果你真的不想使用内置库,你可以尝试这种方式(应该产生与你的 C 代码完全相同的输出):

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 ?但是collections.Counter是最好的方法,它是内置的,为什么不使用它呢?

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 .如果我理解正确,你正在创建b作为一个列表来计算每个号码的出现的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.然后通过字典检查重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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