求出列表lists中每个元素出现的次数
方法一:使用函数Counter,可以迅速获取list中每个元素出现的次数
from collections import Counter
lists = [1, 2, 5, 1, 1, 5, 6, 3, 3, 2, 2, 4, 8]
result = Counter(lists)
print(result)
# 结果如下:
{1: 3, 2: 3, 5: 2, 6: 1, 3: 2, 4: 1, 8: 1}
方法二:使用for循环
result = ['python', 'java', 'python', 'flask', 'django', 'flask']
result_dic = {}
for item_str in result:
if item_str not in result_dic:
result_dic[item_str] = 1
else:
result_dic[item_str] += 1
print(result_dic)
# 输出结果如下:
{'python': 2, 'java': 1, 'flask': 2, 'django': 1}
方法三:利用list中的函数count,获取每个元素的出现次数
list1 = [1, 5, 5, 2, 2, 2, 1, 3]
def all_list(list1):
result = {}
for i in set(list1):
result[i] = list1.count(i)
return result
print(all_list(list1))
# 输出结果如下:
{1: 2, 2: 3, 3: 1, 5: 2}
方法四:利用Numpy索引,获取每个元素的出现次数
import numpy as np
list2 = [5, 5, 5, 8, 8, 9, 1]
def num(lis):
lis = np.array(lis)
key = np.unique(lis)
result = {}
for k in key:
mask = (lis == k)
list_new = lis[mask]
v = list_new.size
result[k] = v
return result
# 输出结果如下:
{5: 3, 8: 2, 9: 1, 1: 1}