在 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]]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP