python method of counting occurrence frequency and sorting for a given iterable set

  • 2020-12-19 21:08:04
  • OfStack

Given an iterable sequence, the occurrence times of the values are counted:

Method 1:


def get_counts(sequence):
 counts = {}
 for x in sequence:
  if x in counts:
   counts[x] += 1
  else:
   counts[x] = 1
 return counts

Method 2:

Take advantage of the collections built into python


from collections import defaultdict

def get_counts2(sequence):
 counts = defaultdict(int) # All values will be initialized 0
 for x in sequence:
  counts[x] +=1 
 return counts

Method 3:


from collections import Counter

counts = Counter(sequence)
# Where you can use counts.most_common(10) Yeah, the ones that come up the most 10 In reverse order 

Then sort the obtained statistics:


def top_count(count_dic, n=10): # Take the largest by default n=10 A value 
 value_key_pairs = [(count,data) for counts,data in cout_dict.items()]
 value_key_pairs.sort()
 #sorted(value_key_pairs)  A mixture of both 
 return value_key_pairs[-n:]

Related articles: