在 Python 中將每個數字的出現次數作為子列表新增
我們有一個元素為數字的列表。許多元素多次出現。我們希望建立子列表,以便每個元素的頻率及其本身。
使用 for 和 append
在這種方法中,我們將列表中的每個元素與其後的所有其他元素進行比較。如果匹配,則計數將遞增,並且元素和計數都將構成一個子列表。將建立一個列表,該列表應包含顯示每個元素及其頻率的子列表。
示例
def occurrences(list_in): for i in range(0, len(listA)): a = 0 row = [] if i not in listB: for j in range(0, len(listA)): # matching items from both positions if listA[i] == listA[j]: a = a + 1 row.append(listA[i]) row.append(a) listB.append(row) # Eliminate repetitive list items for j in listB: if j not in list_uniq: list_uniq.append(j) return list_uniq # Caller code listA = [13,65,78,13,12,13,65] listB = [] list_uniq = [] print("Number of occurrences of each element in the list:\n") print(occurrences(listA))
輸出
執行以上程式碼將得到以下結果:
Number of occurrences of each element in the list: [[13, 3], [65, 2], [78, 1], [12, 1]]
使用 Counter
我們使用 collections 模組中的 counter 方法。它將給出列表中每個元素的計數。然後我們宣告一個新的空列表,並將每個專案的鍵值對以元素及其計數的形式新增到新列表中。
示例
from collections import Counter def occurrences(list_in): c = Counter(listA) new_list = [] for k, v in c.items(): new_list.append([k, v]) return new_list listA = [13,65,78,13,12,13,65] print("Number of occurrences of each element in the list:\n") print(occurrences(listA))
輸出
執行以上程式碼將得到以下結果:
Number of occurrences of each element in the list: [[13, 3], [65, 2], [78, 1], [12, 1]]
廣告