我试图创建一个程序,如果你输入一个单词,它会打印出单词的每个字母以及该单词出现在该单词中的次数。
EG;当我输入" aaaarggh"时,输出应为" 4 r 1 g 2 h 1"。
def compressed (word):
count = 0
index = 0
while index < len(word):
letter = word[index]
for letter in word:
index = index + 1
count = count + 1
print(letter, count)
break
print("Enter a word:")
word = input()
compressed(word)
到目前为止,它只打印出单词中的每个字母和位置。 感谢任何帮助,谢谢!
(不使用dict方法)
答案 0 :(得分:2)
只需键入(对于Python 2.7 +):
import collections
dict(collections.Counter('aaaarggh'))
具有:
{'a': 4, 'g': 2, 'h': 1, 'r': 1}
答案 1 :(得分:1)
a="aaaarggh"
d={}
for char in set(a):
d[char]=a.count(char)
print(d)
输出
{'a': 4, 'h': 1, 'r': 1, 'g': 2}
答案 2 :(得分:1)
试试这个,你可以使用它会返回dict类型
from collections import Counter
print(Counter("aaaarggh"))
答案 3 :(得分:0)
使用dict
实现它的一种方法:
def compressed(word):
letters = dict()
for c in word:
letters[c] = letters.get(c, 0) + 1
for key, value in letters.items():
print(f'{value}{key}', end=' ')
答案 4 :(得分:0)
Counter
简洁明了。但这是使用defaultdict
的替代方法,它是dict
的子类。
from collections import defaultdict
test_input = "aaaarggh"
d = defaultdict(int)
for letter in test_input:
d[letter] += 1
https://docs.python.org/3.6/library/collections.html#defaultdict-examples