簡體   English   中英

在 Python 中查找數組中整數出現的次數

[英]Find the count of the occurrences of an integer in an array 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]]++;
  }    
} 

我試過這樣做 -

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

但我得到

IndexError: list index out of range

有辦法解決嗎?

使用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

歡迎來到 Python 世界,你是 C 開發者! ;) 您可以在此處刪除分號。

您在這里的b是一個包含 0 個元素的 Python 列表,您不能以這種方式在其中獲取或設置元素: b[i]如果索引為 i 的元素尚不存在。

但是有很多方法可以做你想做的事。 如果你真的不想使用內置庫,你可以嘗試這種方式(應該產生與你的 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)

但是collections.Counter是最好的方法,它是內置的,為什么不使用它呢?

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

如果我理解正確,你正在創建b作為一個列表來計算每個號碼的出現的a 這樣,您可以創建一個可能更容易的字典:

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

然后通過字典檢查重復。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM