我们有一个列表,其元素为数字。许多元素多次出现。我们要创建子列表,以便每个元素的频率以及元素本身。
在这种方法中,我们将列表中的每个元素与其后的所有其他元素进行比较。如果存在匹配项,则计数将增加,并且元素和计数都将被存入。将列出其中应包含每个元素及其频率的列表。
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]]
我们使用来自集合模块的计数器方法。它将给出列表中每个元素的计数。然后,我们声明一个新的空列表,并将元素形式的每个项目的键值对及其计数添加到新列表中。
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]]