在 Python 中将每个数字的出现次数添加为子列表

pythonserver side programmingprogramming

我们有一个列表,其元素为数字。许多元素多次出现。我们想要创建子列表,以便每个元素的频率以及元素本身。

使用 for 和 append

在这种方法中,我们将列表中的每个元素与其后的每个其他元素进行比较。如果匹配,则计数将递增,并且元素和计数都将变成一个 subsist。将创建列表,该列表应包含显示每个元素及其频率的 subsist。

示例

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]]

使用计数器

我们使用 collections 模块中的计数器方法。它将给出列表中每个元素的计数。然后我们声明一个新的空列表,并将每个项目的键值对以元素形式及其计数添加到新列表中。

示例

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]]

相关文章