简体   繁体   中英

Function to take a list of integers and count the highest repeated value

Need a function to take a list of integers and return the highest repeated value.

For example: take [4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2] and return (2,5) because there are 5 copies of the value 2.

You can do this pretty easily using Counter.

from collections import Counter

a = [4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]

def count_duplicates(list_of_integers):
  a = Counter(list_of_integers)
  return a.most_common()[0]

count = count_duplicates(a)

print(count)

The output from that gives you (2, 5)

Inbuilt max , set and count methods:

def countMax(arr):
    item = max(set(arr), key=arr.count)
    return (item, arr.count(item))

print(countMax([4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]))

Prints (2, 5) .

You can use defaultdict to achieve this:

from collections import defaultdict

def highest_repeated_value(nums):
  cache = defaultdict(int)
  for i in nums:
    cache[i] += 1
  return max(cache.items(), key=lambda x: x[1])


nums = [4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]
print(highest_repeated_value(nums))

Please note that if nums = [4, 4, 4, 4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2] then there are five 4s and five 2s . However, the result will be (4, 5) ie five 4s .

If your using numpy and list contains all non-negative ints , you can use numpy.bincounts :

import numpy

def highest_repeated_value(nums):
    counts = numpy.bincount(nums)
    num = numpy.argmax(counts)
    val = numpy.max(counts)
    return num, val

nums = [4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]
print(highest_repeated_value(nums))

If you just want to work in python without using numpy , collections.Counter is a good way to handle it.

from collections import Counter

def highest_repeated_value(nums):
  return Counter(nums).most_common()[0]

nums = [4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]
print(highest_repeated_value(nums))

We can utilize tuple to keep track the highest repeated value, like so:

def find_highest_repeated(input_list):
    counter = {}
    highest_repeated = (0, 0, )

    for item in input_list:
        counter[item] = counter[item] + 1 if counter.get(item) is not None else 1
        if counter[item] > highest_repeated[1]:
            highest_repeated = (item, counter[item], )

    return highest_repeated

find_highest_repeated([4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]) # (2, 5)

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM