**Enter**
How are you How is it going
If you enter it like this
**output**
How : 2
are : 1
you : 1
is : 1
it : 1
going : 1
I'm planning to make a program so that it comes out like this
dic = {}
a=input().split()
for i in range(len(a)):
word=a[i]
count=a.count(word)
dic[word]=count
print(dic)
I keep writing it with {key:~, key:~,...It comes out like }, but like the example above, I want to ask you how to program and how to count the number of words without using a.count(word).
python
I changed it a lot, but now that I think about it, I didn't need a dic! Instead, I added a list and added elements to prevent duplication.
a=input().split()
arr = []
for i in range(len(a)):
word=a[i]
count=a.count(word)
if word in arr:
continue
else:
print(word, end=' : ')
print(count)
arr.append(word)
------------------------------------------------------------------------------------------------------------------------------------------+
I have a question, and the conditional if word in arr is the conditional, "Is there already an element in the list?"
If there was already an element in the list, I continued it to prevent duplication
If there are no elements in the list, I want to print them out.
How do I reverse the condition of if word in arr?
from collections import counter
dic = Counter(input().split())
for i in dic:
print(i+" : "+str(dic.get(i)))
If you do this, you will get the result you want. I wrote the counter but not the count.
© 2024 OneMinuteCode. All rights reserved.