0

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.

5 Answers 5

3

You can use count method:

['the','is','the','for','who','the','which'].count('the')

In your case, you could do something like:

count = a.count('the')
print(",".join(f'the{idx + 1}' for idx in range(count)))
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

2
a = ['the','is','the','for','who','the','which']
result = [item + str(idx) for idx, item in enumerate(filter(lambda _: _ == "the", a), 1)]

Comments

0
a=['the','is','the','for','who','the','which']
j=1
for val in a:
    if val == 'the':
        print(val + str(j))
        j+=1

1 Comment

In my head, 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.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.