从随机系列中找出 出现次数最多的元素:两种方法
#!/usr/bin/env python #coding:utf-8 #@Author:Andy print("Generate the random list:") from random import randint list1 = [randint(1, 20) for x in range(30)] print(list1) # use the elements as key ,set times 0 print("Initial Times:") dict1 = dict.fromkeys(list1, 0) print(dict1) for x in list1: dict1[x] += 1 print("Get the max times key:") max_times =max(dict1.items(), key = lambda x :x[1]) print('The max one:') print(max_times) print("**********") print("Second method:") from collections import Counter dict2 = Counter(list1) print('The max one:') max_times1 = dict2.most_common(1)[0] print(max_times1)