Counting elements in a list

If you need to count elements in a list you could code this:

from collections import Counter
a = [1,2,3,1,1,2,2,3]
b = Counter(a)
print(b)

The result being this:

Counter({1: 3, 2: 3, 3: 2})

But you can do it also like this:

k = {}
for v in a:
	if v in k:
		k[v] += 1
	else:
		k[v] = 1

print(k)

The result:

{1: 3, 2: 3, 3: 2}

Counting words

If you want you can do so, to count the words in a string:

rej = """
Two households, both alike in dignity,
In fair Verona, where we lay our scene,
From ancient grudge break to new mutiny,
Where civil blood makes civil hands unclean.
From forth the fatal loins of these two foes
A pair of star-cross'd lovers take their life;
Whose misadventured piteous overthrows
Do with their death bury their parents' strife.
The fearful passage of their death-mark'd love,
And the continuance of their parents' rage,
Which, but their children's end, nought could remove,
Is now the two hours' traffic of our stage;
The which if you with patient ears attend,
What here shall miss, our toil shall strive to mend.
"""

def wordcount(a):
	a = a.replace(",","").replace(".","").replace(";","").split()
	k = {}
	for v in a:
		if v in k:
			k[v] += 1
		else:
			k[v] = 1
	return k

w = wordcount(rej)
print(w)

The result:

{'Two': 1, 'households': 1, 'both': 1, 'alike': 1, 'in': 1, 'dignity': 1, 'In': 1, 'fair': 1, 'Verona': 1, 'where': 1, 'we': 1, 'lay': 1, 'our': 3, 'scene': 1, 'From': 2, 'ancient': 1, 'grudge': 1, 'break': 1, 'to': 2, 'new': 1, 'mutiny': 1, 'Where': 1, 'civil': 2, 'blood': 1, 'makes': 1, 'hands': 1, 'unclean': 1, 'forth': 1, 'the': 3, 'fatal': 1, 'loins': 1, 'of': 5, 'these': 1, 'two': 2, 'foes': 1, 'A': 1, 'pair': 1, "star-cross'd": 1, 'lovers': 1, 'take': 1, 'their': 6, 'life': 1, 'Whose': 1, 'misadventured': 1, 'piteous': 1, 'overthrows': 1, 'Do': 1, 'with': 2, 'death': 1, 'bury': 1, "parents'": 2, 'strife': 1, 'The': 2, 'fearful': 1, 'passage': 1, "death-mark'd": 1, 'love': 1, 'And': 1, 'continuance': 1, 'rage': 1, 'Which': 1, 'but': 1, "children's": 1, 'end': 1, 'nought': 1, 'could': 1, 'remove': 1, 'Is': 1, 'now': 1, "hours'": 1, 'traffic': 1, 'stage': 1, 'which': 1, 'if': 1, 'you': 1, 'patient': 1, 'ears': 1, 'attend': 1, 'What': 1, 'here': 1, 'shall': 2, 'miss': 1, 'toil': 1, 'strive': 1, 'mend': 1}


Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.