Python - 列表中索引處的出現百分比


本文中,使用者將學習列表中索引處的出現百分比。確定列表或陣列中給定索引處特定值的出現百分比是資料分析或處理中的常見任務。這種計算可以提供有關資料分佈和趨勢的洞察資訊。在本文中,我們將研究解決此問題的兩種不同策略,討論它們的演算法,提供獲得所需結果的程式碼片段,然後比較這些策略。

例如 -

Given list :  [4, 2, 3, 1, 5, 6, 7] 

假設值為 3 在索引 2 處出現,則在這種情況下,出現百分比將為 14.29%,因為它只出現一次。

方法

為了使用 Python 查詢索引處的出現百分比,我們可以遵循兩種方法 -

  • 利用樸素迭代。

  • 利用列表推導。

讓我們深入瞭解這兩種方法 -

利用樸素迭代

初始策略採用簡單的迭代過程。將迭代列表中的每個條目,將其與目標索引處的元素進行比較,並跟蹤出現的次數。然後透過將計數除以整個列表的長度來確定出現百分比。

演算法

以下是使用 Python 查詢索引處的出現百分比的演算法 -

  • 步驟 1 - 建立一個函式,將值和索引作為引數。

  • 步驟 2 - 使用變數 count 來儲存指定索引處值出現的次數。

  • 步驟 3 - 建立一個迴圈,遍歷所有值。

  • 步驟 4 - 檢查值,如果值與指定索引處的值匹配,則遞增 count 值。

  • 步驟 5 - 透過將計數除以值的總數來計算出現百分比。

  • 步驟 6 - 返回出現百分比。

  • 步驟 7 - 透過傳遞值來呼叫函式並顯示結果。

示例

# Create a function that takes values as well as indexes as a parameter
def percentage_occurence_compute(value, index):
   # take a variable count to store the occurrence of value at the index specified
   count = 0
   # Run a loop for all the items in the values
   for item in value:
      # If the value is matched for the value at the specified index 
      # then increment the count value
      if item == value[index]:
         count += 1
   percentage_occurrence = (count / len(value)) * 100
   return percentage_occurrence

# Create an instance of values
value =  [4, 2, 3, 1, 5, 6, 7]
index = 2
percentage = percentage_occurence_compute(value, index)
print(f"The percentage occurrence of {value[index]} at index {index} is {percentage}%.")

輸出

The percentage occurrence of 3 at index 2 is 14.285714285714285%.

利用列表推導

利用 Python 的列表推導功能是後續方法。使用列表推導過濾原始列表以生成一個新列表,該列表僅包含與目標索引處的值匹配的項。然後將過濾後的列表的長度除以原始列表的整個長度以確定出現百分比。

演算法

以下是使用 Python 查詢索引處的出現百分比的演算法 -

  • 步驟 1 - 建立一個函式,將值和索引作為引數。

  • 步驟 2 - 透過僅提供指定索引處的項來過濾列表。

  • 步驟 3 - 計算過濾列表和給定值的百分比。

  • 步驟 4 - 調整影像大小並藉助 skimage 計算 psnr。返回 psnr 值。

  • 步驟 5 - 呼叫上述函式並傳遞兩個影像路徑。

  • 步驟 6 - 顯示 psnr 值。

示例

#Create a function that takes values as well as indexes as a parameter
def percentage_occurence_compute(value, index):
   # Filter list by finding only item given at any specified index
   filtered_list = [item for item in value if item == value[index]]
   # Compute the percentage for the filtered list and the given value
   percentage_occurrence = (len(filtered_list) / len(value)) * 100
   # return the computed value
   return percentage_occurrence

# Create an example of the list
value =  [4, 2, 3, 1, 5, 6, 7]
index = 2
# Call the above function
percentage = percentage_occurence_compute(value, index)
# Display the result
print(f"The percentage occurrence of {value[index]} at index {index} is {percentage}%.")

輸出

The percentage occurrence of 3 at index 2 is 14.285714285714285%.

結論

在本文中,我們研究了兩種計算 Python PSNR(峰值信噪比)的方法。在影像和影片處理的背景下,PSNR 是一個重要的統計資料,用於評估數字資料的質量。可以使用均方誤差 (MSE) 方法或 skimage 庫來確定精確的 PSNR 分數並評估數字訊號的質量。

更新於: 2023年10月18日

141 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.