.方法一,可以使用字典的方法Counter来实现:输出的结果是个字典。
记得安装对应的包
#需要导入Counter方法
from collections import Counter
List = [1,2,3,1,2,3,"python",4,5,"python"]
list = dict(Counter(List))
print({key:value for key,value in list.items() if value > 1})
=>{1: 2, 2: 2, 3: 2, 'python': 2}
2.方法二,使用遍历列表元素来实现。这也是比较容易想到的方法,输出的结果也是个字典。
def counter_num(List):
#定义一个字典
counter={}
for i in List:
#List.count(i)统计列表元素对应的个数
if List.count(i) > 1:
counter[i] = List.count(i)
print(counter)
counter_num(List) => {1: 2, 2: 2, 3: 2, 'python': 2}