There is an array in which a bunch of duplicate elements. I need to output the contents of a specific element of this array and how many such elements are in it (output a number).
Array example:

array = ["Bob", "Alex", "Bob", "John"] 

(type 2 bob etc.)

    5 answers 5

    The easiest way to calculate the number of occurrences of all elements is to use the built-in Counter class from the collections module:

     In [4]: from collections import Counter In [5]: array = ["Bob", "Alex", "Bob", "John"] In [6]: c = Counter(array) In [7]: c Out[7]: Counter({'Bob': 2, 'Alex': 1, 'John': 1}) In [8]: c['Bob'] Out[8]: 2 In [9]: c['Unknown'] Out[9]: 0 

      There is a list.count method

       >>> array.count("Bob") 2 >>> array.count("John") 1 >>> dict((x, array.count(x)) for x in set(array) if array.count(x) > 1) {'Bob': 2} 
      • 2
        This is a quadratic algorithm. If it is not known in advance that the length of the array is small, then a linear algorithm, such as in a solution with Counter, is preferable to use. Even for small arrays, if there are no special reasons, Counter should be preferred here. - jfs

      Generally speaking, this is a reduce-task. But in Python, extremely weak means for operations with associative arrays ( dict ). In particular, two such arrays can not just be taken and folded. You will have to first decompose them into tuples, then fold them, and at the end connect them back. As a result, a one-liner that could look decent would look something like this:

       reduce(lambda x,y: dict(x.items()+[(y,x[y]+1 if y in x else 1)]), array, dict()) 
      • one
        Honestly, do not need to write on Python. Note that the standard library has a collections module, and there is a Counter in it. - idle sign
      • @idlesign I know. I even made a reservation that I myself didn’t like this decision. About Counter also in the know. - Shamov
      • Hm, then it’s not clear why to suggest using the impactor properties of a spray gun without offering a hammer. - idle sign
      • one
        @idlesign Hammer offered without me. I see my task in offering non-trivial solutions. - Shamov

      as an option

       array = ["Bob", "Alex", "Bob", "John"] array_d = {}.fromkeys(array, 0) for a in array: array_d[a] += 1 print(array_d) 

      or

       array_d = {} for a in array: try: array_d[a] += 1 except KeyError: array_d[a] = 1 
      • one
        It is worth {}.fromkeys to replace dict.fromkeys . Both work, but fromkeys is a class method, so it’s better not to call through an instance ( {} ). Additionally, this solution bypasses the array two times. Option with Counter single pass (which arbitrary iterator allows to use). - jfs

      For example, like this:

       array = ["Bob", "Alex", "Bob", "John"]; result = {i: array.count(i) for i in array}; 

      And the question is, how can I get the key by the maximum value?