我需要接受一个字符串输入,并且每个字符只计算一次字符的出现次数(不应该对同一个字符重复)并将其打印在列表或set或tuple中。但是我没有得到理想的结果。
代码:
string1 = input('Enter your string: ')
for letter in string1:
string2 = string1.count(letter,0)
ss = str(string2)
print(ss)
输出:
Enter your string: ggddg
3
3
2
2
3
答案 0 :(得分:3)
根据您希望输出的外观,您可以使用collections.Counter,它具有类似dict的界面:
from collections import Counter
user_input = input('Enter your string: ')
counts = Counter(user_input)
print(counts) # prints: Counter({'g': 3, 'd': 2})
答案 1 :(得分:1)
您打印的每个不同字符的计数次数与字符串中显示的次数相同。首先是g
,有3个g
,因此您打印3,然后另一个g
来,您再次计算并打印。我想你要打印的是3'g'和2'd'。
试试这个:
letters = {}
for c in input("Enter your string: "):
if c not in letters:
letters[c] = 1
else:
letters[c] += 1
print(letters)
输出:
Enter your string: ggddg
{'g': 3, 'd': 2}
答案 2 :(得分:0)
试试这个:
string1 = input('Enter your string: ')
print('\n'.join(list(set([i+' '+str(string1.count(i)) for i in string1]))))
输出:
Enter your string: aaabbcca
c 2
a 4
b 2
或试试这个:
string1 = input('Enter your string: ')
print('\n'.join(list(set(map(lambda x: x+' '+str(string1.count(x)),string1)))))
输出:
Enter your string: aaabbcca
c 2
a 4
b 2
答案 3 :(得分:0)
您可以使用dict存储该信息
d = {}
for c in string1:
try:
d[c] += 1
except KeyError:
d[c] = 1
print(d)
答案 4 :(得分:0)
我认为这就是您想要的,请使用示例用户字符串
进行尝试#!python3
# sample user string: fdshjkfdskhjlfdsjklfdsevcxzm,.czxm,.
user_string = input('Enter your string: ')
all_letters = []
unique_letters = []
for letter in user_string:
all_letters.append(letter)
for unique in all_letters:
if unique in unique_letters:
pass
else:
unique_letters.append(unique)
for item in unique_letters:
print(item + ' = ' + str(all_letters.count(item)))
# results
'''
f = 4
d = 4
s = 4
h = 2
j = 3
k = 3
l = 2
e = 1
v = 1
c = 2
x = 2
z = 2
m = 2
, = 2
. = 2
'''
答案 5 :(得分:0)
@Mahesh ,使用set
和dictionary
可以有效地计算字符串中字符的出现次数。
在http://rextester.com/KQV63040在线试用。
注意:我使用
json
模块来打印字典。您可以使用
OrderedDict
collections
模块根据插入情况保留字典中的键顺序。
import json
string1 = input('Enter your string: ').strip()
unique_letters = set(string1)
letters_occurrences = {}
for letter in unique_letters:
letters_occurrences[letter] = string1.count(letter)
print() # newline
# Pretty printing the dictionary
print(json.dumps(letters_occurrences, indent=4))
»输出
Enter your string: abbacddabbc
{
"b": 4,
"a": 3,
"d": 2,
"c": 2
}