删除重复项并在特定输出中打印字符串

2024-06-01 00:22:23 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我想要得到的输出:

Please enter sentence: Hello Python!
' ' 1
'!' 1
'H' 1
'P' 1
'e' 1
'h' 1
'l' 2
'n' 1
'o' 2
't' 1
'y' 1
[' ', '!', 'H', 'P', 'e', 'h', 'l', 'n', 'o', 't', 'y']

这是我尝试的代码:

from collections import OrderedDict
def rmdup(str1):
    return "".join(OrderedDict.fromkeys(str1))
str = input("Please enter sentence: ")
sorted_str = sorted(str)
str1 = []
for i in range(len(str)):
    j = sorted_str.count(sorted-str[i])
    str1 = list(rmdup(str1))
    print(repr(sorted_str) + '\t' + repr(j))
print(str1)

这是我得到的结果:

Please enter sentence: Hello Python!
' ' 1
'!' 1
'H' 1
'P' 1
'e' 1
'h' 1
'l' 2
'l' 2
'n' 1
'o' 2
'o' 2
't' 1
'y' 1
[' ', '!', 'H', 'P', 'e', 'h', 'l', 'n', 'o', 't', 'y']

Tags: 代码fromimporthellocollectionssentenceordereddictsorted
1条回答
网友
1楼 · 发布于 2024-06-01 00:22:23

您可以使用collections.Counter容器

from collections import Counter

sentence = input('Please enter a sentence: ')
counter = Counter(sentence)
for key, value in counter.items():
    print("'{}' {}".format(key, value))

print([key for key in counter.keys()])

相关问题 更多 >