【问题标题】:Removing duplicates and printing the string in specific output删除重复项并在特定输出中打印字符串
【发布时间】:2020-03-25 15:53:11
【问题描述】:

这是我想要得到的输出:

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']

【问题讨论】:

  • 您不能将- 作为变量名的一部分。另一方面,下划线_ 是有效的。调用变量sorted_str 而不是sorted-str。但是你应该有一个语法错误。下次也请发布您遇到的错误。如果我们的程序执行,那么不仅要发布预期的输出,还要发布你得到的输出
  • 太好了,你得到了一个对你有帮助的答案。我提出了一个编辑请求以使您的代码正常工作。请下次尝试小心发布导致问题的代码。我很确定,上面带有sorted-str 而不是sorted_str 的代码根本不起作用,也没有输出您在问题中建议的结果。如果您发布的代码可以复制和粘贴并允许重现您的问题,那么您会让每个人的生活变得更加轻松。尽情享受吧

标签: python python-3.x string duplicates


【解决方案1】:

您可以使用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()])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-04
    • 2016-07-17
    • 2016-08-30
    • 2012-10-21
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 2015-05-07
    相关资源
    最近更新 更多