0

I need for my studies to build self count function in python3 like this:

given a list:

a = [30, 15, 15, 30, 2, 3, 4, 5]

30:2, 15:2, 2:1, 3:1, 4:1, 5:1

nums = [35, 40, 46, 47, 34, 36, 37, 38, 39, 
        40, 41, 42, 43, 42, 47, 37, 39, 46, 
        40, 31, 50, 45, 39, 38, 34, 47, 44]
nums.sort()
print(nums)
c = []
for i in range(len(nums)):
    if nums[i] == nums[i+1]:
        c.extend([nums[i], i])
        nums=nums[1::]
    else:
        c.append(nums[i])
        print(c)
ywbaek
  • 2,971
  • 3
  • 9
  • 28

4 Answers4

1

Python has builtin functionality for this, albeit a list object is not the way to go:

a = [30, 15, 15, 30, 2, 3, 4, 5]

from collections import Counter

ct = Counter(a)
print(ct)
# Counter({30: 2, 15: 2, 2: 1, 3: 1, 4: 1, 5: 1})

Or - using a defaultdict:

from collections import defaultdict
dct = defaultdict(int)

for number in a:
    dct[str(number)] += 1

print(dct)
# defaultdict(<class 'int'>, {'30': 2, '15': 2, '2': 1, '3': 1, '4': 1, '5': 1})

Note that you can easily achieve it with pure Python alone:

dct = {}
for number in a:
    key = str(number)
    try:
        dct[key] += 1
    except KeyError:
        dct[key] = 1
print(dct)
# {'30': 2, '15': 2, '2': 1, '3': 1, '4': 1, '5': 1}

Lastly, you could use a dict comprehension with set():

dct = {str(key): a.count(key) for key in set(a)}
print(dct)
# {'2': 1, '3': 1, '4': 1, '5': 1, '15': 2, '30': 2}
Jan
  • 42,290
  • 8
  • 54
  • 79
1

Two easy ways to do it.

  1. Using Counter:

    nums=[35, 40, 46, 47, 34, 36, 37, 38, 39, 40, 41, 42, 43, 42, 47, 37, 39, 46, 40, 31, 50, 45, 39, 38,
    from collections import Counter
    nums_freq = Counter(nums)
    print (nums_freq)
  1. Using inline loop:

    nums=[35, 40, 46, 47, 34, 36, 37, 38, 39, 40, 41, 42, 43, 42, 47, 37, 39, 46, 40, 31, 50, 45, 39, 38,
    34, 47, 44]
    nums_freq ={i:nums.count(i) for i in nums}
    print (nums_freq)

Output:

{35: 1, 40: 3, 46: 2, 47: 3, 34: 2, 36: 1, 37: 2, 38: 2, 39: 3, 41: 1, 42: 2, 43: 1, 31: 1, 50: 1, 45: 1, 44: 1}
Thaer A
  • 2,243
  • 1
  • 10
  • 14
0

Use the Counter from collections:

c = collections.Counter([35, 40, 46, 47, 34, 36, 37, 38, 39, 40, 41, 42, 43, 42, 47, 37, 39, 46, 40, 31, 50, 45, 39, 38, 34, 47, 44])

for _ in c.most_common():
    print(f"{_[0]}:{_[1]}")
Alexander Kosik
  • 669
  • 3
  • 10
0

Here using dictionary is appropriate data structure. Please refer https://docs.python.org/3/tutorial/datastructures.html

def myCounter(myList):
    myDict = dict()
    for number in myList:
        if number in myDict:
            myDict[number]+=1
        else:
            myDict[number]=1
    myDisplay(myDict)
    return myDict

def myDisplay(myDict):
    for key in myDict:
        print(key,":",myDict[key],ends=",")
Mandar Autade
  • 336
  • 2
  • 12