I have a list:
a = ['the','is','the','for','who','the','which'].
I want to count the occurrence of 'the'. For example, here 'the' appears 3 times, so it will print: the1,the2,the3.
You can use The collections module.
from collections import Counter
a = ['the','is','the','for','who','the','which']
dict_a = Counter(a)
n = dict_a["the"] # number of occurrence of word "the" in list a
for i in range(1,n+1):
print("the%d" % i)
The dict_a = Counter(a) gives a dictionary that has unique words as keys of the dictionary and the number of occurrences of each word in the list as the value of each key.
a=['the','is','the','for','who','the','which']
j=1
for val in a:
if val == 'the':
print(val + str(j))
j+=1
j should start at 0 and j += 1 should happen before the print. It's nitpicking but it makes more sense to me to start the counter at zero.I like to use regex for this, as this gives you more freedom when comparig strings. Since you also want to append the number of occurrences to a string, you might need a loop.
Here is my take on your question:
import re
a = ['the','is','the','for','who','the','which']
out = []
value = "the"
occur = 0
for input in a:
result = re.search(value, input)
if result:
occur += 1
out.append(value + str(occur))
for output in out:
print(output)
Changing the value variable will make your code try to match other strings (say "who"). You could also use the regex101 website to find best regex fits for all cases.
Below is the resulting outout:
the1
the2
the3