This question already has an answer here:
这个问题在这里已有答案:
- Counting repeated characters in a string in Python 15 answers
- 在Python 15中对字符串中的重复字符进行计数
- How do you remove duplicates from a list whilst preserving order? 28 answers
- 如何在保留订单的同时从列表中删除重复项? 28个答案
Essentially i have to write a program that counts how many time each letter occurs in a string. I got that working but letters duplicate, for example. If the string was hello it would output:
基本上我必须编写一个程序来计算每个字母出现在字符串中的时间。例如,我得到了它,但字母重复。如果字符串是hello,它将输出:
- h 1
- h 1
- e 1
- e 1
- l 2
- l 2
- l 2
- l 2
- o 1
- o 1
When i need it to output:
当我需要输出时:
- h 1
- h 1
- e 1
- e 1
- l 2
- l 2
- o 1
- o 1
The way i've done it so far is without importing anything and my code looks like:
到目前为止我完成它的方式是没有导入任何东西,我的代码看起来像:
input_text = input('Enter some text: ')
s = input_text.lower()
length_s = len(s)
l = 0
while length_s > 0:
if s[l].isalpha():
print(s[l], s.count(s[l]))
l += 1
length_s -=1
else:
l += 1
length_s -=1
2 个解决方案
#1
5
You can use a collections.Counter
for your use case, it is a dict subclass for counting hashable objects (example - characters in a string) . Example -
您可以将collections.Counter用作您的用例,它是用于计算可哈希对象的dict子类(示例 - 字符串中的字符)。示例 -
>>> from collections import Counter
>>> c = Counter('hello')
>>> c
Counter({'l': 2, 'h': 1, 'o': 1, 'e': 1})
>>> for i,x in c.items():
... print('{} - {}'.format(i,x))
...
l - 2
h - 1
o - 1
e - 1
Without using imports, you can use set()
to store the characters that have already been seen. (This is done so that order is also maintained) -
不使用导入,您可以使用set()来存储已经看过的字符。 (这样做也是为了维持秩序) -
input_text = input('Enter some text: ')
s = input_text.lower()
seen = set()
for c in s:
if c not in seen:
print(c, s.count(c))
seen.add(c)
#2
2
If you don't want to import anything you could do something like this to get a dictionary:
如果您不想导入任何内容,可以执行以下操作来获取字典:
s = input_text.lower()
countDict = {}
for char in s:
if (char not in countDict):
countDict[char] = 1
else:
countDict[char] += 1
#1
5
You can use a collections.Counter
for your use case, it is a dict subclass for counting hashable objects (example - characters in a string) . Example -
您可以将collections.Counter用作您的用例,它是用于计算可哈希对象的dict子类(示例 - 字符串中的字符)。示例 -
>>> from collections import Counter
>>> c = Counter('hello')
>>> c
Counter({'l': 2, 'h': 1, 'o': 1, 'e': 1})
>>> for i,x in c.items():
... print('{} - {}'.format(i,x))
...
l - 2
h - 1
o - 1
e - 1
Without using imports, you can use set()
to store the characters that have already been seen. (This is done so that order is also maintained) -
不使用导入,您可以使用set()来存储已经看过的字符。 (这样做也是为了维持秩序) -
input_text = input('Enter some text: ')
s = input_text.lower()
seen = set()
for c in s:
if c not in seen:
print(c, s.count(c))
seen.add(c)
#2
2
If you don't want to import anything you could do something like this to get a dictionary:
如果您不想导入任何内容,可以执行以下操作来获取字典:
s = input_text.lower()
countDict = {}
for char in s:
if (char not in countDict):
countDict[char] = 1
else:
countDict[char] += 1